-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path447719203.html
More file actions
1253 lines (916 loc) · 89.5 KB
/
Copy path447719203.html
File metadata and controls
1253 lines (916 loc) · 89.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" data-default-color-scheme="auto">
<head>
<meta charset="UTF-8">
<link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
<link rel="icon" href="/img/fluid.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="theme-color" content="#2f4154">
<meta name="author" content="FangZhou">
<meta name="keywords" content="Vue,React,Nodejs,blogs,frontend,web,developer,programmer">
<meta name="description" content="Node.js运行时环境学习笔记,涵盖模块化、全局API和核心模块的全面总结">
<meta property="og:type" content="article">
<meta property="og:title" content="Node.js学习笔记">
<meta property="og:url" content="http://arkpln.github.io/447719203.html">
<meta property="og:site_name" content="Ark的技术博客">
<meta property="og:description" content="Node.js运行时环境学习笔记,涵盖模块化、全局API和核心模块的全面总结">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://arkpln.github.io/Node-js%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/npm-install%E6%B5%81%E7%A8%8B.webp">
<meta property="og:image" content="http://arkpln.github.io/Node-js%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/re-sub.webp">
<meta property="article:published_time" content="2025-07-02T12:28:37.000Z">
<meta property="article:modified_time" content="2026-01-26T04:01:09.928Z">
<meta property="article:author" content="FangZhou">
<meta property="article:tag" content="nodejs">
<meta property="article:tag" content="backend">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="npm">
<meta property="article:tag" content="commonjs">
<meta property="article:tag" content="esmodules">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://arkpln.github.io/Node-js%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/npm-install%E6%B5%81%E7%A8%8B.webp">
<title>Node.js学习笔记 - Ark的技术博客</title>
<link rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css">
<link rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css">
<link rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css">
<!-- 主题依赖的图标库,不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1749284_5i9bdhy70f8.css">
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_1736178_k526ubmyhba.css">
<link rel="stylesheet" href="/css/main.css">
<link id="highlight-css" rel="stylesheet" href="/css/highlight.css">
<link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css">
<script id="fluid-configs">
var Fluid = window.Fluid || {};
Fluid.ctx = Object.assign({}, Fluid.ctx)
var CONFIG = {"hostname":"arkpln.github.io","root":"/","version":"1.9.8","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"leancloud":{"app_id":"mEwkD7geCX7RWNO8srhDE2oP-gzGzoHsz","app_key":"4EF76hyiVA1QILHZThVbfoat","server_url":"https://mewkd7ge.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false},"umami":{"src":null,"website_id":null,"domains":null,"start_time":"2024-01-01T00:00:00.000Z","token":null,"api_server":null}},"search_path":"/local-search.xml","include_content_in_search":true};
if (CONFIG.web_analytics.follow_dnt) {
var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
}
</script>
<script src="/js/utils.js"></script>
<script src="/js/color-schema.js"></script>
<meta name="google-site-verification" content="5KfTZvtlydmBIzY97rVo-caP5jljAfmD3Qs3sBzY2Go"><style>ins.adsbygoogle[data-ad-status="unfilled"] { display: none !important; }</style>
<meta name="generator" content="Hexo 7.3.0"></head>
<body>
<header>
<div class="header-inner" style="height: 70vh;">
<nav id="navbar" class="navbar fixed-top navbar-expand-lg navbar-dark scrolling-navbar">
<div class="container">
<a class="navbar-brand" href="/">
<strong>Ark的技术博客</strong>
</a>
<button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<div class="animated-icon"><span></span><span></span><span></span></div>
</button>
<!-- Collapsible content -->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto text-center">
<li class="nav-item">
<a class="nav-link" href="/" target="_self">
<i class="iconfont icon-home-fill"></i>
<span>快乐老家</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/archives/" target="_self">
<i class="iconfont icon-archive-fill"></i>
<span>笔岚档案</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/categories/" target="_self">
<i class="iconfont icon-category-fill"></i>
<span>文以类聚</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/tags/" target="_self">
<i class="iconfont icon-tags-fill"></i>
<span>按标签阅览</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about/" target="_self">
<i class="iconfont icon-user-fill"></i>
<span>联系我</span>
</a>
</li>
<li class="nav-item" id="search-btn">
<a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
<i class="iconfont icon-search"></i>
</a>
</li>
<li class="nav-item" id="color-toggle-btn">
<a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
<i class="iconfont icon-dark" id="color-toggle-icon"></i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="banner" class="banner" parallax="true" style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
<div class="full-bg-img">
<div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
<div class="banner-text text-center fade-in-up">
<div class="h2">
<span id="subtitle" data-typed-text="Node.js学习笔记"></span>
</div>
<div class="mt-3">
<span class="post-meta">
<i class="iconfont icon-date-fill" aria-hidden="true"></i>
<time datetime="2025-07-02 20:28" pubdate>
July 2, 2025 pm
</time>
</span>
</div>
<div class="mt-1">
<span class="post-meta mr-2">
<i class="iconfont icon-chart"></i>
17k words
</span>
<span class="post-meta mr-2">
<i class="iconfont icon-clock-fill"></i>
143 mins
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<main>
<div class="container-fluid nopadding-x">
<div class="row nomargin-x">
<div class="side-col d-none d-lg-block col-lg-2">
<aside class="sidebar d-none d-xl-block" style="margin-right:-1rem;z-index:-1"><ins class="adsbygoogle" style="display:flex;justify-content:center;min-width:160px;max-width:300px;width:100%;height:600px;position:sticky;top:2rem" data-ad-client="ca-pub-3240358922862141" data-ad-slot="6522434837"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script></aside>
</div>
<div class="col-lg-8 nopadding-x-md">
<div class="container nopadding-x-md" id="board-ctn">
<div id="board">
<article class="post-content mx-auto">
<h1 id="seo-header">Node.js学习笔记</h1>
<div class="markdown-body">
<h1 id="Node-js学习笔记"><a href="#Node-js学习笔记" class="headerlink" title="Node.js学习笔记"></a>Node.js学习笔记</h1><p>Node.js 是一个开源、跨平台的 JavaScript 运行时环境。</p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>适合IO密集型运算(libuv和cpp底层的功劳),不适合CPU密集型计算(单线程),可用于前后端开发。</p>
<p>前端:Vue Angular React Nuxtjs</p>
<p>后端:</p>
<ol>
<li><p>Serverless</p>
</li>
<li><p>Web应用:Express,Nextjs,koa</p>
</li>
<li><p>RPC服务:gRPC</p>
</li>
<li><p>爬虫:Puppeteer</p>
</li>
<li><p>BFF层</p>
</li>
<li><p>及时性应用:Socket.io</p>
</li>
</ol>
<p>桌面端:</p>
<ol>
<li><p>Electron</p>
</li>
<li><p>Tauri</p>
</li>
<li><p>NW.js</p>
</li>
</ol>
<p>移动端:</p>
<ol>
<li><p>Weex</p>
</li>
<li><p>Ionic</p>
</li>
<li><p>React Native</p>
</li>
</ol>
<p>基建端:</p>
<ol>
<li><p>Webpack Vite</p>
</li>
<li><p>less scss</p>
</li>
<li><p>babel swc</p>
</li>
<li><p>inquire</p>
</li>
</ol>
<p>CI/CD 反代 单元测试等都可以使用Node.js.</p>
<p><em>我靠,怎么Nodejs什么都能干啊!</em></p>
<h2 id="npm"><a href="#npm" class="headerlink" title="npm"></a>npm</h2><p><strong>npm</strong>是Nodejs的包管理工具。</p>
<h3 id="常用npm命令"><a href="#常用npm命令" class="headerlink" title="常用npm命令"></a>常用npm命令</h3><ol>
<li><p><code>npm init</code>:初始化空白包,创建package.json</p>
</li>
<li><p><code>npm run script</code>: 运行npm命令(需要在package.json定义)</p>
</li>
<li><p><code>npm install</code>:安装一个包或一组包,并会在当前目录存放一个<em>node_modules</em>,简写为<code>npm i ...</code></p>
</li>
<li><p><code>npm install <package-name> --save</code>:安装指定包,并将其添加到<code>package.json</code>,</p>
</li>
<li><p><code>npm uninstall <package-name></code>:卸载指定包</p>
</li>
<li><p><code>npm config list</code> :查看Node npm版本,npm源,runtime目录等信息</p>
</li>
<li><p><code>npm config registry</code>:查看npm源</p>
</li>
<li><p><code>npm config set registry URLs</code>:设置npm源</p>
</li>
<li><p><code>npm login</code>:登录npm</p>
</li>
<li><p><code>npm publish</code>:将包发布到npm</p>
</li>
</ol>
<h3 id="关于package-json"><a href="#关于package-json" class="headerlink" title="关于package.json"></a>关于package.json</h3><ol>
<li><p><code>"version":"1.0.0"</code></p>
<ul>
<li><p>第一位主版本号,针对重大更新或改动</p>
</li>
<li><p>第二位次版本号,针对功能更新</p>
</li>
<li><p>第三位修订号。针对bug修复</p>
</li>
</ul>
</li>
<li><p><code>"scripts":{...}</code><br>运行npm命令</p>
</li>
<li><p><code>"repository:{...}"</code><br>设置仓库信息和地址</p>
</li>
<li><p><code>"author":...</code><br>作者信息</p>
</li>
<li><p><code>"license":...</code><br>项目许可证</p>
</li>
<li><p>关于”dependencies”</p>
<ol>
<li><p><code>"devDependencies":{...}</code><br>开发所需的依赖,通过<code>npm i <package-name> -D</code>添加到package.json,例如<code>webpack</code>,<code>vite</code>,<code>rollup</code>等开发环境需要的依赖</p>
</li>
<li><p><code>"dependencies:{...}"</code><br>生产环境所需的依赖</p>
</li>
<li><p><code>"peerDependencies":{...}</code><br>给插件编写人员或npm包的开发人员使用</p>
</li>
</ol>
</li>
</ol>
<h3 id="npm-install原理"><a href="#npm-install原理" class="headerlink" title="npm install原理"></a>npm install原理</h3><blockquote>
<p>首先安装的依赖都会存放在根目录的node_modules,默认采用扁平化的方式安装,并且排序规则.bin第一个然后@系列,再然后按照首字母排序abcd等,并且使用的算法是广度优先遍历,在遍历依赖树时,npm会首先处理项目根目录下的依赖,然后逐层处理每个依赖包的依赖,直到所有依赖都被处理完毕。在处理每个依赖时,npm会检查该依赖的版本号是否符合依赖树中其他依赖的版本要求,如果不符合,则会尝试安装适合的版本</p>
</blockquote>
<p>详细见:<a target="_blank" rel="noopener" href="https://juejin.cn/post/7261119531891490877">Npm install原理</a></p>
<p><img src="/./Node-js%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/npm-install%E6%B5%81%E7%A8%8B.webp" srcset="/img/loading.gif" lazyload title="流程图"></p>
<p>注意:</p>
<ol>
<li><p>如果项目中package.json与package-lock.json的依赖和版本不一致,则拉取package.json的依赖为准,并覆盖package-lock.json</p>
</li>
<li><p>npm install在检查npm config时,遵循项目级npmrc->用户级npmrc->全局npmrc->npm内置npmrc的顺序</p>
</li>
<li><p>package-lock.json中的”name”,”integrity”,”version”信息会生产一个key索引,用于比较本地的缓存</p>
</li>
</ol>
<h3 id="npm-run原理"><a href="#npm-run原理" class="headerlink" title="npm run原理"></a>npm run原理</h3><p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7261235534663368741">npm run原理</a></p>
<p>当前项目搜索是否存在<em>node/modules/.bin</em>,其次是全局,再其次是环境变量,如果没有就报错.</p>
<p>npm run也有生命周期,可以在package.json中的”scripts”设置”predev”和”postdev”参数执行相关文件.</p>
<h3 id="npx"><a href="#npx" class="headerlink" title="npx"></a>npx</h3><blockquote>
<p>npx是一个命令行工具,它是npm 5.2.0版本中新增的功能。它允许用户在不安装全局包的情况下,运行已安装在本地项目中的包或者远程仓库中的包。</p>
<p>npx的作用是在命令行中运行node包中的可执行文件,而不需要全局安装这些包。这可以使开发人员更轻松地管理包的依赖关系,并且可以避免全局污染的问题。它还可以帮助开发人员在项目中使用不同版本的包,而不会出现版本冲突的问题。</p>
</blockquote>
<p><strong>npx的作用</strong></p>
<ol>
<li><p>避免全局安装</p>
</li>
<li><p>总是使用最新版本</p>
</li>
<li><p>执行任意npm包</p>
</li>
<li><p>可以执行Github gist等公开的JavaScript文件</p>
</li>
</ol>
<h3 id="发布npm包"><a href="#发布npm包" class="headerlink" title="发布npm包"></a>发布npm包</h3><p><strong>步骤:</strong></p>
<ol>
<li><p>创建npm账号(注意是npm官方源)</p>
</li>
<li><p>登录npm账号</p>
</li>
<li><p><code>npm publish</code>发布</p>
</li>
</ol>
<h3 id="npm私服"><a href="#npm私服" class="headerlink" title="npm私服"></a>npm私服</h3><p>好处:</p>
<ul>
<li><p>可以离线使用,私有化部署</p>
</li>
<li><p>提供包的安全性,更好的管理包</p>
</li>
<li><p>提高包的下载速度</p>
</li>
</ul>
<p><strong>步骤:</strong></p>
<ol>
<li><p>安装verdaccio</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">npm i verdaccio -g<br></code></pre></td></tr></table></figure>
</li>
<li><p>启动npm私服服务</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">verdaccio --listen 5000<br></code></pre></td></tr></table></figure>
</li>
<li><p>创建npm私服账户</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">npm adduser --registry http://localhost:5000/<br></code></pre></td></tr></table></figure>
</li>
<li><p>发布到npm私服</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs shell">npm publish --registry http://localhost:5000/<br></code></pre></td></tr></table></figure></li>
</ol>
<p>注:如果已经设置好registry可以直接切换镜像然后更新</p>
<h2 id="Nodejs的模块化"><a href="#Nodejs的模块化" class="headerlink" title="Nodejs的模块化"></a>Nodejs的模块化</h2><p>Nodejs的模块化规范遵循两套:<strong><code>CommonJS</code></strong> 和 <strong><code>ESModules</code></strong></p>
<h3 id="CommonJS规范"><a href="#CommonJS规范" class="headerlink" title="CommonJS规范"></a>CommonJS规范</h3><p>package.json中设置属性<code>"type"</code>为<code>"commonjs"</code></p>
<p><strong>五种模式</strong></p>
<ol>
<li><p>使用<code>require()</code>引入自己编写的模块</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'./test.js'</span>)<br></code></pre></td></tr></table></figure>
</li>
<li><p>引入第三方模块</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> md5 = <span class="hljs-built_in">require</span>(<span class="hljs-string">"md5"</span>)<br></code></pre></td></tr></table></figure>
</li>
<li><p>引入Nodejs内置模块</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"node:fs"</span>)<br></code></pre></td></tr></table></figure>
</li>
<li><p>引入C++扩展,addon,napi,node-gyp,.node等</p>
</li>
<li><p>引入Json文件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> data = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./data.json'</span>)<br></code></pre></td></tr></table></figure></li>
</ol>
<p>使用 <strong><code>module.exports</code></strong> 导出模块,也可使用ES6的解构赋值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = {<br> <span class="hljs-attr">success</span>:<span class="hljs-number">1</span>,<br>}<br></code></pre></td></tr></table></figure>
<h3 id="ESModules规范"><a href="#ESModules规范" class="headerlink" title="ESModules规范"></a>ESModules规范</h3><p>package.json中设置属性<code>"type"</code>为<code>"module"</code></p>
<p><strong>导入:</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span><br></code></pre></td></tr></table></figure>
<p>ESM不支持引入json,高版本可以强兼容但需要额外的断言且会报警</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> json <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert {<span class="hljs-attr">type</span>:<span class="hljs-string">"json"</span>}<br></code></pre></td></tr></table></figure>
<p><strong>导出:</strong></p>
<p><code>export default</code>只能有一个</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {<br> success :<span class="hljs-number">1</span><br>}<br></code></pre></td></tr></table></figure>
<p>要查看某模块导出的所有内容:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> all <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.js'</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(all)<br></code></pre></td></tr></table></figure>
<h3 id="CJS和ESM的区别"><a href="#CJS和ESM的区别" class="headerlink" title="CJS和ESM的区别"></a>CJS和ESM的区别</h3><ol>
<li><p>Cjs是基于<strong>运行时</strong>的同步加载,ESM是基于<strong>编译时</strong>的异步加载.一般来说,ESM下的import只能在作用域最顶层,若需要动态加载,可以使用import的函数模式(会返回一个Promise对象).</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){<br> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./test.js'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res)<br>})<br>}<br></code></pre></td></tr></table></figure>
</li>
<li><p>CJs可以修改值,但ESM不行</p>
</li>
<li><p>Cjs不可以Tree Shaking,ESM可以</p>
</li>
<li><p>Cjs的顶层<code>this</code>指向模块本身,ESM顶层<code>this</code>指向<code>undefined</code></p>
</li>
</ol>
<h2 id="全局变量-全局API"><a href="#全局变量-全局API" class="headerlink" title="全局变量&全局API"></a>全局变量&全局API</h2><p>在浏览器环境下,可以使用<code>var</code>的关键词将全局变量绑定到<code>window</code>对象上,但是node并不是浏览器环境,因此不存在BOM和DOM,而且使用<code>var</code>定义全局变量也会导致状态提升的问题.</p>
<h3 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h3><p>在nodejs中使用global定义全局变量.在ECMA2020中可使用<code>globalThis</code>作为全局变量,可以自动切换.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">global</span>.<span class="hljs-property">name</span> = <span class="hljs-string">"xxx"</span>;<br></code></pre></td></tr></table></figure>
<h3 id="全局API"><a href="#全局API" class="headerlink" title="全局API"></a>全局API</h3><p>由于nodejs中没有DOM和BOM,除了这些API,其他的ECMAscriptAPI基本都能用,例如<code>setTimeout</code>,<code>Promise</code>,<code>Math</code>,<code>Console</code>等</p>
<h3 id="Nodejs专有API"><a href="#Nodejs专有API" class="headerlink" title="Nodejs专有API"></a>Nodejs专有API</h3><ol>
<li><p><strong><code>__dirname</code></strong><br>表示当前模块的所在目录的绝对路径,<strong>ESM模式下不可使用,可用process.cwd()代替</strong></p>
</li>
<li><p><strong><code>__filename</code></strong></p>
</li>
</ol>
<p> 表示当前模块文件的绝对路径,包括文件名和文件扩展名</p>
<blockquote>
<p><strong><code>__dirname</code> <code>__filename</code> 只能在cjs使用 esm规范没有这两个全局变量</strong></p>
</blockquote>
<ol start="3">
<li><p><strong><code>process</code></strong><br>处理进程相关的内容</p>
<ol>
<li><p><code>process.argv</code>: 这是一个包含命令行参数的数组。第一个元素是Node.js的执行路径,第二个元素是当前执行的JavaScript文件的路径,之后的元素是传递给脚本的命令行参数。 </p>
</li>
<li><p><code>process.env</code>: 这是一个包含当前环境变量的对象。您可以通过<code>process.env</code>访问并操作环境变量。</p>
</li>
<li><p><code>process.cwd()</code>: 这个方法返回当前工作目录的路径。</p>
</li>
<li><p><code>process.on(event, listener)</code>: 用于注册事件监听器。您可以使用<code>process.on</code>监听诸如<code>exit</code>、<code>uncaughtException</code>等事件,并在事件发生时执行相应的回调函数。 </p>
</li>
<li><p><code>process.exit([code])</code>: 用于退出当前的Node.js进程。您可以提供一个可选的退出码作为参数。</p>
</li>
<li><p><code>process.pid</code>: 这个属性返回当前进程的PID(进程ID)。</p>
</li>
</ol>
<p>这些只是<code>process</code>对象的一些常用属性和方法,还有其他许多属性和方法可用于监控进程、设置信号处理、发送IPC消息等。<br>需要注意的是,<code>process</code>对象是一个全局对象,可以在任何模块中直接访问,无需导入或定义。</p>
</li>
<li><p><strong><code>Buffer</code></strong></p>
<ol>
<li>创建 <code>Buffer</code> 实例:</li>
</ol>
<ul>
<li><code>Buffer.alloc(size[, fill[, encoding]])</code>: 创建一个指定大小的新的<code>Buffer</code>实例,初始内容为零。<code>fill</code>参数可用于填充缓冲区,<code>encoding</code>参数指定填充的字符编码。</li>
<li><code>Buffer.from(array)</code>: 创建一个包含给定数组的<code>Buffer</code>实例。</li>
<li><code>Buffer.from(string[, encoding])</code>: 创建一个包含给定字符串的<code>Buffer</code>实例。</li>
</ul>
<ol start="2">
<li>读取和写入数据:</li>
</ol>
<ul>
<li><code>buffer[index]</code>: 通过索引读取或写入<code>Buffer</code>实例中的特定字节。</li>
<li><code>buffer.length</code>: 获取<code>Buffer</code>实例的字节长度。</li>
<li><code>buffer.toString([encoding[, start[, end]]])</code>: 将<code>Buffer</code>实例转换为字符串。</li>
</ul>
<ol start="3">
<li>转换数据:</li>
</ol>
<ul>
<li><code>buffer.toJSON()</code>: 将Buffer实例转换为JSON对象。</li>
<li><code>buffer.slice([start[, end]])</code>: 返回一个新的Buffer实例,其中包含原始Buffer实例的部分内容。</li>
</ul>
<ol start="4">
<li>其他:</li>
</ol>
<ul>
<li><code>Buffer.isBuffer(obj)</code>: 检查一个对象是否是Buffer实例。</li>
<li><code>Buffer.concat(list[, totalLength])</code>: 将一组Buffer实例或字节数组连接起来形成一个新的Buffer实例。</li>
</ul>
</li>
</ol>
<h2 id="CSR-SSR-SEO"><a href="#CSR-SSR-SEO" class="headerlink" title="CSR SSR SEO"></a>CSR SSR SEO</h2><h3 id="概述-1"><a href="#概述-1" class="headerlink" title="概述"></a>概述</h3><p>在node环境下无法直接操作DOM和BOM,可以通过<code>jsdom</code>实现,模拟浏览器的环境</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">JSDOM</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsdom'</span>)<br><br><span class="hljs-keyword">const</span> dom = <span class="hljs-keyword">new</span> <span class="hljs-title function_">JSDOM</span>(<span class="hljs-string">`<!DOCTYPE html><div id='app'></div>`</span>)<br><br><span class="hljs-keyword">const</span> <span class="hljs-variable language_">document</span> = dom.<span class="hljs-property">window</span>.<span class="hljs-property">document</span><br><br><span class="hljs-keyword">const</span> <span class="hljs-variable language_">window</span> = dom.<span class="hljs-property">window</span><br><br><span class="hljs-title function_">fetch</span>(<span class="hljs-string">'https://api.thecatapi.com/v1/images/search?limit=10&page=1'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =></span> res.<span class="hljs-title function_">json</span>()).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">data</span> =></span> {<br> <span class="hljs-keyword">const</span> app = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">'app'</span>)<br> data.<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">item</span>=></span>{<br> <span class="hljs-keyword">const</span> img = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">'img'</span>)<br> img.<span class="hljs-property">src</span> = item.<span class="hljs-property">url</span><br> img.<span class="hljs-property">style</span>.<span class="hljs-property">width</span> = <span class="hljs-string">'200px'</span><br> img.<span class="hljs-property">style</span>.<span class="hljs-property">height</span> = <span class="hljs-string">'200px'</span><br> app.<span class="hljs-title function_">appendChild</span>(img)<br> })<br> fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'./index.html'</span>, dom.<span class="hljs-title function_">serialize</span>())<br>})<br><br><br></code></pre></td></tr></table></figure>
<h3 id="CSR-SSR"><a href="#CSR-SSR" class="headerlink" title="CSR/SSR"></a>CSR/SSR</h3><p>我们上面的操作属于SSR <code>(Server-Side Rendering)</code>服务端渲染请求数据和拼装都在服务端完成,而我们的Vue,react 等框架这里不谈(nuxtjs,nextjs),是在客户端完成渲染拼接的属于CSR<code>(Client-Side Rendering)</code>客户端渲染.</p>
<p>CSR 和 SSR 区别</p>
<ol>
<li><p>页面加载方式:</p>
<ul>
<li>CSR:在 CSR 中,服务器返回一个初始的 HTML 页面,然后浏览器下载并执行 JavaScript 文件,JavaScript 负责动态生成并更新页面内容。这意味着初始页面加载时,内容较少,页面结构和样式可能存在一定的延迟。</li>
<li>SSR:在 SSR 中,服务器在返回给浏览器之前,会预先在服务器端生成完整的 HTML 页面,包含了初始的页面内容。浏览器接收到的是已经渲染好的 HTML 页面,因此初始加载的速度较快。</li>
</ul>
</li>
<li><p>内容生成和渲染:</p>
<ul>
<li>CSR:在 CSR 中,页面的内容生成和渲染是由客户端的 JavaScript 脚本负责的。当数据变化时,JavaScript 会重新生成并更新 DOM,从而实现内容的动态变化。这种方式使得前端开发更加灵活,可以创建复杂的交互和动画效果。</li>
<li>SSR:在 SSR 中,服务器在渲染页面时会执行应用程序的代码,并生成最终的 HTML 页面。这意味着页面的初始内容是由服务器生成的,对于一些静态或少变的内容,可以提供更好的首次加载性能。</li>
</ul>
</li>
<li><p>用户交互和体验:</p>
<ul>
<li>CSR:在 CSR 中,一旦初始页面加载完成,后续的用户交互通常是通过 AJAX 或 WebSocket 与服务器进行数据交互,然后通过 JavaScript 更新页面内容。这种方式可以提供更快的页面切换和响应速度,但对于搜索引擎爬虫和 SEO(搜索引擎优化)来说,可能需要一些额外的处理。</li>
<li>SSR:在 SSR 中,由于页面的初始内容是由服务器生成的,因此用户交互可以直接在服务器上执行,然后服务器返回更新后的页面。这样可以提供更好的首次加载性能和对搜索引擎友好的内容。</li>
</ul>
</li>
</ol>
<p>CSR 应用例如 ToB 后台管理系统 大屏可视化 都可以采用CSR渲染不需要很高的SEO支持</p>
<p>SSR 应用例如 内容密集型应用大部分是ToC 新闻网站 ,博客网站,电子商务,门户网站需要更高的SEO支持</p>
<h2 id="Path-路径模块"><a href="#Path-路径模块" class="headerlink" title="Path-路径模块"></a>Path-路径模块</h2><blockquote>
<p>path模块在不同的操作系统是有差异的(Windows/POSIX)</p>
</blockquote>
<h3 id="POSIX"><a href="#POSIX" class="headerlink" title="POSIX"></a>POSIX</h3><p>Unix,like-unix,macOS,Linux,WSL都遵循POSIX标准,使用正斜杠<code>/</code></p>
<h3 id="Win32"><a href="#Win32" class="headerlink" title="Win32"></a>Win32</h3><p>使用双反斜杠<code>\\</code></p>
<h3 id="兼容性处理方法"><a href="#兼容性处理方法" class="headerlink" title="兼容性处理方法"></a>兼容性处理方法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'\\foo\\bar\\baz\\xm.html'</span>))<br></code></pre></td></tr></table></figure>
<h3 id="Path模块常用方法"><a href="#Path模块常用方法" class="headerlink" title="Path模块常用方法"></a>Path模块常用方法</h3><ol>
<li><p><code>basename</code> :返回给定路径的文件名(含文件扩展名)</p>
</li>
<li><p><code>dirname</code>:返回路径的目录名</p>
</li>
<li><p><code>extname</code>:返回路径的扩展名(带点,形如<code>.html</code>)<br><em>如果没有,返回空字符串;如果有多个点,返回最后一个点后面的内容</em></p>
</li>
<li><p><code>path.join(params)</code>:将多个路径字符串合并为一个字符串</p>
</li>
<li><p><code>path.resolve(params)</code>:解析路径,返回绝对路径;若有多个路径参数则返回最后一个;若只有一个相对路径,返回当前工作目录的绝对路径.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/a'</span>))<br><span class="hljs-comment">// D:\a</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./index.js'</span>))<br><span class="hljs-comment">// D:\Project\Program\Node\index.js</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'D:/Project/Program/Node'</span>,<span class="hljs-string">'./node_modules'</span>,<span class="hljs-string">'./.bin/tldts'</span>))<br><span class="hljs-comment">// D:\Project\Program\Node\node_modules\.bin\tldts</span><br></code></pre></td></tr></table></figure>
</li>
<li><p><code>path.parse()</code>:解析路径,返回对象</p>
</li>
<li><p><code>path.format()</code>:根据传入的对象解析路径</p>
</li>
</ol>
<h2 id="OS-系统模块"><a href="#OS-系统模块" class="headerlink" title="OS-系统模块"></a>OS-系统模块</h2><p>OS模块主要是和操作系统交互的模块</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>API</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><strong>os.type()</strong></td>
<td>它在 Linux 上返回 <code>'Linux'</code>,在 macOS 上返回 <code>'Darwin'</code>,在 Windows 上返回 <code>'Windows_NT'</code></td>
</tr>
<tr>
<td>2</td>
<td><strong>os.platform()</strong></td>
<td>返回标识为其编译 Node.js 二进制文件的操作系统平台的字符串。 该值在编译时设置。 可能的值为 <code>'aix'</code>、<code>'darwin'</code>、<code>'freebsd'</code>、<code>'linux'</code>、<code>'openbsd'</code>、<code>'sunos'</code>、以及 <code>'win32'</code></td>
</tr>
<tr>
<td>3</td>
<td><strong>os.release()</strong></td>
<td>返回操作系统的版本例如10.xxxx win10</td>
</tr>
<tr>
<td>4</td>
<td><strong>os.homedir()</strong></td>
<td>返回用户目录 例如c:\user\xiaoman 原理就是 windows <code>echo %USERPROFILE%</code> posix $HOME</td>
</tr>
<tr>
<td>5</td>
<td><strong>os.arch()</strong></td>
<td>返回cpu的架构 可能的值为 <code>'arm'</code>、<code>'arm64'</code>、<code>'ia32'</code>、<code>'mips'</code>、<code>'mipsel'</code>、<code>'ppc'</code>、<code>'ppc64'</code>、<code>'s390'</code>、<code>'s390x'</code>、以及 <code>'x64'</code></td>
</tr>
<tr>
<td>6</td>
<td><strong>os.cpus()</strong></td>
<td>返回CPU的线程及详细信息</td>
</tr>
<tr>
<td>7</td>
<td><strong>os.networkInterfaces()</strong></td>
<td>返回网络信息</td>
</tr>
</tbody></table>
<h2 id="Process-进程模块"><a href="#Process-进程模块" class="headerlink" title="Process-进程模块"></a>Process-进程模块</h2><ol>
<li><p><code>process.arch()</code>:返回操作系统CPU架构</p>
</li>
<li><p><code>process.cwd()</code>:返回当前的工作目录,可代替<code>__dirname</code>使用</p>
</li>
<li><p><code>process.argv()</code>:获取执行进程后面的参数 返回是一个数组 后面我们讲到命令行交互工具的时候会很有用,各种cli脚手架也是使用这种方式接受配置参数例如webpack</p>
</li>
<li><p><code>process.memoryUsage()</code>:用于获取当前进程的内存使用情况。该方法返回一个对象,其中包含了各种内存使用指标,如 rss(Resident Set Size,常驻集大小)、heapTotal(堆区总大小)、heapUsed(已用堆大小)和 external(外部内存使用量)等</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js">{<br> <span class="hljs-attr">rss</span>: <span class="hljs-number">30932992</span>, <span class="hljs-comment">// 常驻集大小 这是进程当前占用的物理内存量,不包括共享内存和页面缓存。它反映了进程实际占用的物理内存大小</span><br> <span class="hljs-attr">heapTotal</span>: <span class="hljs-number">6438912</span>, <span class="hljs-comment">//堆区总大小 这是 V8 引擎为 JavaScript 对象分配的内存量。它包括了已用和未用的堆内存</span><br> <span class="hljs-attr">heapUsed</span>: <span class="hljs-number">5678624</span>, <span class="hljs-comment">//已用堆大小</span><br> <span class="hljs-attr">external</span>: <span class="hljs-number">423221</span>, <span class="hljs-comment">//外部内存使用量 这部分内存不是由 Node.js 进程直接分配的,而是由其他 C/C++ 对象或系统分配的</span><br> <span class="hljs-attr">arrayBuffers</span>: <span class="hljs-number">17606</span> <span class="hljs-comment">//是用于处理二进制数据的对象类型,它使用了 JavaScript 中的 ArrayBuffer 接口。这个属性显示了当前进程中 ArrayBuffers 的数量</span><br> }<br><br></code></pre></td></tr></table></figure>
</li>
<li><p><code>process.exit()</code>:退出进程</p>
</li>
<li><p><code>process.kill(pid)</code>:杀死进程</p>
</li>
<li><p><code>process.env()</code>:获取或修改当前操作系统的环境变量,但修改只在当前进程生效,不会真正影响系统的环境变量.</p>
</li>
</ol>
<p><strong>注:</strong> 可以使用第三方库<code>cross-env</code>实现环境变量的切换</p>
<h2 id="child-process-子进程模块"><a href="#child-process-子进程模块" class="headerlink" title="child_process-子进程模块"></a>child_process-子进程模块</h2><ol>
<li><p><code>exec('command',(err,stdout,stderr)=>{})</code>在shell执行命令,异步方法,有回调函数,<code>stdout</code>是输出,<code>stderr</code>是错误信息.</p>
</li>
<li><p><code>execSync()</code>:功能同上,但是同步方法,不需要回调函数.</p>
</li>
<li><p><code>spawn()</code>:执行命令(shell命令无上限,返回流,实时返回)</p>
</li>
<li><p><code>spawnSync()</code>:执行命令(同步方法)<br>cwd <string> 子进程的当前工作目录。<br>env <Object> 环境变量键值对。<br>encoding <string> 默认为 ‘utf8’。<br>shell <string> 用于执行命令的 shell。 在 UNIX 上默认为 ‘/bin/sh’,在 Windows 上默认为 process.env.ComSpec。 详见 Shell Requirements 与 Default Windows Shell。<br>timeout <number> 默认为 0。<br>maxBuffer <number> stdout 或 stderr 允许的最大字节数。 默认为 200*1024。 如果超过限制,则子进程会被终止。 查看警告: maxBuffer and Unicode。<br>killSignal <string> | <integer> 默认为 ‘SIGTERM’。<br>uid <number> 设置该进程的用户标识。(详见 setuid(2))<br>gid <number> 设置该进程的组标识。(详见 setgid(2))</p>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> {spawn} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'child_process'</span>)<br><br><span class="hljs-keyword">const</span> {stdout} = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'netstat'</span>)<br><br>stdout.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>,<span class="hljs-function">(<span class="hljs-params">msg</span>)=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg.<span class="hljs-title function_">toString</span>())<br>})<br><br>stdout.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>,<span class="hljs-function">(<span class="hljs-params">msg</span>)=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"End"</span>)<br>})<br></code></pre></td></tr></table></figure>
<ol start="5">
<li><code>execFile()</code>执行脚本文件</li>
<li><code>execFileSync()</code>:同上,同步方法</li>
<li><code>fork()</code>:创建子进程,但仅限于js模块,父子进程可相互通信</li>
</ol>
<h2 id="Events-事件模块"><a href="#Events-事件模块" class="headerlink" title="Events-事件模块"></a>Events-事件模块</h2><p>Node.js核心API都采用异步事件驱动架构,通过有效的方法监听事件状态的变化,在变化时做出相应的动作.</p>
<h3 id="事件模型"><a href="#事件模型" class="headerlink" title="事件模型"></a>事件模型</h3><p><code>发布-订阅设计模式</code></p>
<img title src="./Node-js学习笔记/re-sub.webp" srcset="/img/loading.gif" lazyload alt>
<p>当一个发布者有新消息时,就将这个消息发布到调度中心。调度中心就会将这个消息通知给所有订阅者。这就实现了发布者和订阅者之间的解耦,发布者和订阅者不再直接依赖于彼此,他们可以独立地扩展自己.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs js"><br><span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>)<br><br><span class="hljs-comment">// 发布订阅模式 off on emit once</span><br><br><span class="hljs-keyword">const</span> bus = <span class="hljs-keyword">new</span> <span class="hljs-title function_">eventEmitter</span>()<br><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">fn</span> = (<span class="hljs-params">name</span>)=>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name)<br>}<br><br><br><span class="hljs-comment">//订阅一个事件</span><br>bus.<span class="hljs-title function_">on</span>(<span class="hljs-string">'test'</span>,fn)<br><span class="hljs-comment">//移除一个事件订阅</span><br>bus.<span class="hljs-title function_">off</span>(<span class="hljs-string">'test'</span>,fn)<br><span class="hljs-comment">//仅执行一次</span><br>bus.<span class="hljs-title function_">once</span>(<span class="hljs-string">'testonce'</span>,<span class="hljs-function">()=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"Only run once."</span>)<br>})<br><br><span class="hljs-comment">//发布事件</span><br>bus.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'test'</span>,<span class="hljs-string">"xm"</span>)<br><br>bus.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'testonce'</span>)<br>bus.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'testonce'</span>)<br></code></pre></td></tr></table></figure>
<p>监听消息数量默认是<strong>10</strong>个,可以通过调用<code>setMaxListeners</code>传入数量.</p>
<h2 id="Util-工具模块"><a href="#Util-工具模块" class="headerlink" title="Util-工具模块"></a>Util-工具模块</h2><p>util是Nodejs内部提供的实用工具类API.</p>
<ol>
<li><strong><code>util.promisify()</code></strong> :将回调函数包装为Promise类型</li>
</ol>
<p><em>注:</em> 如果有多个返回值,res为js对象;若只有一个返回值,res即是本身</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span><br><span class="hljs-keyword">import</span> util <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span><br><br><span class="hljs-keyword">const</span> execPromise = util.<span class="hljs-title function_">promisify</span>(exec)<br><br><span class="hljs-title function_">execPromise</span>(<span class="hljs-string">'node -v'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res,<span class="hljs-string">'res'</span>)<br>}).<span class="hljs-title function_">catch</span>(<span class="hljs-function"><span class="hljs-params">err</span>=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err,<span class="hljs-string">'err'</span>)<br>})<br><br></code></pre></td></tr></table></figure>
<ol start="2">
<li><strong><code>util.callbackify</code></strong> :将promise类型的方法变成 回调函数。</li>
<li><strong><code>util.format</code></strong>:输入格式化<ul>
<li><code>%s</code>: <code>String</code> 将用于转换除 <code>BigInt</code>、<code>Object</code> 和 <code>-0</code> 之外的所有值。 <code>BigInt</code> 值将用 <code>n</code> 表示,没有用户定义的 <code>toString</code> 函数的对象使用具有选项 <code>{ depth: 0, colors: false, compact: 3 }</code> 的 <code>util.inspect()</code> 进行检查。</li>
<li><code>%d</code>: <code>Number</code> 将用于转换除 <code>BigInt</code> 和 <code>Symbol</code> 之外的所有值。</li>
<li><code>%i</code>: <code>parseInt(value, 10)</code> 用于除 <code>BigInt</code> 和 <code>Symbol</code> 之外的所有值。</li>
<li><code>%f</code>: <code>parseFloat(value)</code> 用于除 <code>Symbol</code> 之外的所有值。</li>
<li><code>%j</code>: JSON。 如果参数包含循环引用,则替换为字符串 <code>'[Circular]'</code>。</li>
<li><code>%o</code>: <code>Object</code>. 具有通用 JavaScript 对象格式的对象的字符串表示形式。 类似于具有选项 <code>{ showHidden: true, showProxy: true }</code> 的 <code>util.inspect()</code>。 这将显示完整的对象,包括不可枚举的属性和代理。</li>
<li><code>%O</code>: <code>Object</code>. 具有通用 JavaScript 对象格式的对象的字符串表示形式。 类似于没有选项的 <code>util.inspect()</code>。 这将显示完整的对象,但不包括不可枚举的属性和代理。</li>
<li><code>%c</code>: <code>CSS</code>. 此说明符被忽略,将跳过任何传入的 CSS。</li>
<li><code>%%</code>: 单个百分号 (<code>'%'</code>)。 这不消费参数。</li>
</ul>
</li>
</ol>
<h2 id="Fs-文件模块"><a href="#Fs-文件模块" class="headerlink" title="Fs-文件模块"></a>Fs-文件模块</h2><h3 id="1-读取文件"><a href="#1-读取文件" class="headerlink" title="1. 读取文件"></a>1. 读取文件</h3><p> <code>fs.readFile()</code>:异步方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br><span class="hljs-comment">// 异步方法</span><br>fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'./index.txt'</span>,{<br> <span class="hljs-attr">encoding</span>:<span class="hljs-string">'utf-8'</span>,<br> <span class="hljs-attr">flag</span>:<span class="hljs-string">'r'</span><br>},<span class="hljs-function">(<span class="hljs-params">err,data</span>)=></span>{<br> <span class="hljs-keyword">if</span>(err){<br> <span class="hljs-keyword">throw</span> err<br> }<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data)<br>})<br><br><br></code></pre></td></tr></table></figure>
<p><code>fs.readFileSync()</code>:同步方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br><span class="hljs-comment">// 同步方法,会导致代码阻塞</span><br><span class="hljs-keyword">const</span> res = fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./index.txt'</span>)<br><span class="hljs-comment">// sync方法的返回值都是buffer流,需要toString方法处理后才能得到原始值</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res.<span class="hljs-title function_">toString</span>())<br></code></pre></td></tr></table></figure>
<p><code>fs2.readFile().then()</code>:Promise包装方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>)<br><br><span class="hljs-comment">//Promise方法</span><br>fs2.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'./index.txt'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf-8'</span>))<br>})<br></code></pre></td></tr></table></figure>
<p><code>fs.createReadStream()</code>:流式读取文件(适合大文件)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//流式读取-大文件处理</span><br><br><span class="hljs-keyword">const</span> readStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./index.txt'</span>)<br><br>readStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>,<span class="hljs-function">(<span class="hljs-params">chunk</span>)=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf-8'</span>))<br>})<br><br>readStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>,<span class="hljs-function">()=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"读取完成"</span>)<br>})<br></code></pre></td></tr></table></figure>
<h3 id="2-文件夹操作"><a href="#2-文件夹操作" class="headerlink" title="2. 文件夹操作"></a>2. 文件夹操作</h3><p><code>fs.mkdirSync()</code>:创建文件夹,<code>recursive:true</code>允许多层文件夹嵌套</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 创建文件夹</span><br>fs.<span class="hljs-title function_">mkdirSync</span>(<span class="hljs-string">'./works/native'</span>,{<br> <span class="hljs-attr">recursive</span>:<span class="hljs-literal">true</span><br>})<br></code></pre></td></tr></table></figure>
<p><code>fs.rmdirSync()</code>:删除文件夹,若要删除单文件可用<code>fs.rmSync()</code></p>
<h3 id="3-重命名"><a href="#3-重命名" class="headerlink" title="3.重命名"></a>3.重命名</h3><p><code>fs.renameSync('old','new')</code>:重命名文件</p>
<h3 id="4-文件监听"><a href="#4-文件监听" class="headerlink" title="4.文件监听"></a>4.文件监听</h3><p><code>fs.watch(filePath,(event,filename)=>{})</code>:监听文件事件变化 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br>fs.<span class="hljs-title function_">watchFile</span>(<span class="hljs-string">'./index.txt'</span>,<span class="hljs-function">(<span class="hljs-params">event,filename</span>)=></span>{<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event)<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(filename)<br>})<br></code></pre></td></tr></table></figure>
<p><code>fs.watchFile(filePath,(cur,pre)=>{})</code>:监听文件的元数据信息变化</p>
<h3 id="5-写入文件"><a href="#5-写入文件" class="headerlink" title="5.写入文件"></a>5.写入文件</h3><p><code>fs.writeFileSync(fileName,contentString)</code>:向指定路径下文件写入内容(默认覆盖方法)</p>
<p><em>注:</em>,第三个参数<code>{flag:'a'}</code>表示追加,<code>fs.appendFileSync()</code>也可实现相同功能</p>
<ul>
<li><p><code>'a'</code>: 打开文件进行追加。 如果文件不存在,则创建该文件。</p>
</li>
<li><p><code>'ax'</code>: 类似于 <code>'a'</code> 但如果路径存在则失败。</p>
</li>
<li><p><code>'a+'</code>: 打开文件进行读取和追加。 如果文件不存在,则创建该文件。</p>
</li>
<li><p><code>'ax+'</code>: 类似于 <code>'a+'</code> 但如果路径存在则失败。</p>
</li>
<li><p><code>'as'</code>: 以同步模式打开文件进行追加。 如果文件不存在,则创建该文件。</p>
</li>
<li><p><code>'as+'</code>: 以同步模式打开文件进行读取和追加。 如果文件不存在,则创建该文件。</p>
</li>
<li><p><code>'r'</code>: 打开文件进行读取。 如果文件不存在,则会发生异常。</p>
</li>
<li><p><code>'r+'</code>: 打开文件进行读写。 如果文件不存在,则会发生异常。</p>
</li>
<li><p><code>'rs+'</code>: 以同步模式打开文件进行读写。 指示操作系统绕过本地文件系统缓存。<br>这主要用于在 NFS 挂载上打开文件,因为它允许跳过可能过时的本地缓存。 它对 I/O 性能有非常实际的影响,因此除非需要,否则不建议使用此标志。<br>这不会将 <code>fs.open()</code> 或 <code>fsPromises.open()</code> 变成同步阻塞调用。 如果需要同步操作,应该使用类似 <code>fs.openSync()</code> 的东西。</p>
</li>
<li><p><code>'w'</code>: 打开文件进行写入。 创建(如果它不存在)或截断(如果它存在)该文件。</p>
</li>
<li><p><code>'wx'</code>: 类似于 <code>'w'</code> 但如果路径存在则失败。</p>
</li>
<li><p><code>'w+'</code>: 打开文件进行读写。 创建(如果它不存在)或截断(如果它存在)该文件。</p>
</li>
<li><p><code>'wx+'</code>: 类似于 <code>'w+'</code> 但如果路径存在则失败。</p>
</li>
</ul>
<p><code>fs.createWriteStream(filePath)</code>:创建可写流,适合大量数据的写入.</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><span class="hljs-keyword">const</span> verse = [<br> <span class="hljs-string">'你若三冬来'</span>,<br> <span class="hljs-string">'换我一城雪白'</span>,<br> <span class="hljs-string">'相思风中开'</span>,<br>]<br><span class="hljs-keyword">const</span> writeStream = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./index.txt'</span>)<br><br>verse.<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">item</span>=></span>{<br> writeStream.<span class="hljs-title function_">write</span>(item + <span class="hljs-string">'\n'</span>)<br>})<br><br>writeStream.<span class="hljs-title function_">end</span>()<br></code></pre></td></tr></table></figure>
<h3 id="6-软连接-硬链接"><a href="#6-软连接-硬链接" class="headerlink" title="6.软连接/硬链接"></a>6.软连接/硬链接</h3><p><code>fs.linkSync(filePath,newFilePath)</code>:创建硬链接文件,类似共享文件,可用于文件备份</p>
<p><code>fs.symlinkSync(filePath,newFilePath)</code>:创建硬链接,类似win的快捷方式,源文件删除后无效.</p>
<h2 id="Zlib-解压缩"><a href="#Zlib-解压缩" class="headerlink" title="Zlib-解压缩"></a>Zlib-解压缩</h2><p>在 Node.js 中,<code>zlib</code> 模块提供了对数据压缩和解压缩的功能,以便在应用程序中减少数据的传输大小和提高性能。该模块支持多种压缩算法,包括 Deflate、Gzip 和 Raw Deflate。</p>
<p>Gzip流式压缩:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>)<br><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br><span class="hljs-keyword">const</span> readStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./index.txt'</span>)<br><span class="hljs-keyword">const</span> writeStream = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./index.txt.gz'</span>) <span class="hljs-comment">//gz后缀</span><br>readStream.<span class="hljs-title function_">pipe</span>(zlib.<span class="hljs-title function_">createGzip</span>()).<span class="hljs-title function_">pipe</span>(writeStream)<br></code></pre></td></tr></table></figure>
<p>Gzip流式解压:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>)<br><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br><span class="hljs-keyword">const</span> readStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./index.txt'</span>)<br><span class="hljs-keyword">const</span> writeStream = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./index.txt.gz'</span>) <span class="hljs-comment">//gz后缀</span><br>readStream.<span class="hljs-title function_">pipe</span>(zlib.<span class="hljs-title function_">createGunzip</span>()).<span class="hljs-title function_">pipe</span>(writeStream)<br></code></pre></td></tr></table></figure>
<p>Defalte同理,改为<code>createDefalte()</code>压缩,<code>createInfalte()</code>解压即可.</p>
<p>Gzip文件解压:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>)<br><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>)<br><br><br><span class="hljs-keyword">let</span> content = <span class="hljs-string">'...'</span><br><span class="hljs-keyword">const</span> res = zlib.<span class="hljs-title function_">gzipSync</span>() <span class="hljs-comment">//同步方法</span><br></code></pre></td></tr></table></figure>
<h2 id="Http-http服务"><a href="#Http-http服务" class="headerlink" title="Http-http服务"></a>Http-http服务</h2><p>“http” 模块是 Node.js 中用于创建和处理 HTTP 服务器和客户端的核心模块。它使得构建基于 HTTP 协议的应用程序变得更加简单和灵活。</p>
<ol>
<li>创建 Web 服务器:你可以使用 “http” 模块创建一个 HTTP 服务器,用于提供 Web 应用程序或网站。通过监听特定的端口,服务器可以接收客户端的请求,并生成响应。你可以处理不同的路由、请求方法和参数,实现自定义的业务逻辑。</li>
<li>构建 RESTful API:”http” 模块使得构建 RESTful API 变得简单。你可以使用 HTTP 请求方法(如 GET、POST、PUT、DELETE 等)和路径来定义 API 的不同端点。通过解析请求参数、验证身份和权限,以及生成相应的 JSON 或其他数据格式,你可以构建强大的 API 服务。</li>
<li>代理服务器:”http” 模块还可以用于创建代理服务器,用于转发客户端的请求到其他服务器。代理服务器可以用于负载均衡、缓存、安全过滤或跨域请求等场景。通过在代理服务器上添加逻辑,你可以对请求和响应进行修改、记录或过滤。</li>
<li>文件服务器:”http” 模块可以用于创建一个简单的文件服务器,用于提供静态文件(如 HTML、CSS、JavaScript、图像等)。通过读取文件并将其作为响应发送给客户端,你可以轻松地构建一个基本的文件服务器。</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>); <span class="hljs-comment">// 引入 http 模块</span><br><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <span class="hljs-comment">// 引入 url 模块</span><br><br><span class="hljs-comment">// 创建 HTTP 服务器,并传入回调函数用于处理请求和生成响应</span><br>http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {<br> <span class="hljs-keyword">const</span> { pathname, query } = url.<span class="hljs-title function_">parse</span>(req.<span class="hljs-property">url</span>, <span class="hljs-literal">true</span>); <span class="hljs-comment">// 解析请求的 URL,获取路径和查询参数</span><br><br> <span class="hljs-keyword">if</span> (req.<span class="hljs-property">method</span> === <span class="hljs-string">'POST'</span>) { <span class="hljs-comment">// 检查请求方法是否为 POST</span><br> <span class="hljs-keyword">if</span> (pathname === <span class="hljs-string">'/post'</span>) { <span class="hljs-comment">// 检查路径是否为 '/post'</span><br> <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;<br> req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {<br> data += chunk; <span class="hljs-comment">// 获取 POST 请求的数据</span><br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);<br> });<br> req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {<br> res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>); <span class="hljs-comment">// 设置响应头的 Content-Type 为 'application/json'</span><br> res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">200</span>; <span class="hljs-comment">// 设置响应状态码为 200</span><br> res.<span class="hljs-title function_">end</span>(data); <span class="hljs-comment">// 将获取到的数据作为响应体返回</span><br> });<br> } <span class="hljs-keyword">else</span> {<br> res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>); <span class="hljs-comment">// 设置响应头的 Content-Type 为 'application/json'</span><br> res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>; <span class="hljs-comment">// 设置响应状态码为 404</span><br> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Not Found'</span>); <span class="hljs-comment">// 返回 'Not Found' 作为响应体</span><br> }<br> } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.<span class="hljs-property">method</span> === <span class="hljs-string">'GET'</span>) { <span class="hljs-comment">// 检查请求方法是否为 GET</span><br> <span class="hljs-keyword">if</span> (pathname === <span class="hljs-string">'/get'</span>) { <span class="hljs-comment">// 检查路径是否为 '/get'</span><br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(query.<span class="hljs-property">a</span>); <span class="hljs-comment">// 打印查询参数中的键名为 'a' 的值</span><br> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'get success'</span>); <span class="hljs-comment">// 返回 'get success' 作为响应体</span><br> }<br> }<br>}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">98</span>, <span class="hljs-function">() =></span> {<br> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server is running on port 98'</span>); <span class="hljs-comment">// 打印服务器启动的信息</span><br>});<br><br></code></pre></td></tr></table></figure>
<p>Http请求</p>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-keyword">POST</span> <span class="hljs-string">http://localhost:98/post/xxx</span> <span class="hljs-meta">HTTP/1.1</span><br><br><span class="language-pgsql">Content-<span class="hljs-keyword">Type</span>: application/<span class="hljs-type">json</span></span><br><span class="language-pgsql"></span><br><span class="language-pgsql">{</span><br><span class="language-pgsql"> "name":"小满zs"</span><br><span class="language-pgsql">}</span><br><span class="language-pgsql"></span><br><span class="language-pgsql"></span><br><span class="language-pgsql"><span class="hljs-keyword">GET</span> http://localhost:<span class="hljs-number">98</span>/<span class="hljs-keyword">get</span>?a=<span class="hljs-number">1</span>&b=<span class="hljs-number">2</span> HTTP/<span class="hljs-number">1.1</span></span><br><span class="language-pgsql"></span><br><span class="language-pgsql"></span><br></code></pre></td></tr></table></figure>
</div>
<hr>
<div>
<div class="post-metas my-3">
<div class="post-meta mr-3 d-flex align-items-center">
<i class="iconfont icon-category"></i>
<span class="category-chains">
<span class="category-chain">
<a href="/categories/backend/" class="category-chain-item">backend</a>
</span>
</span>
</div>
<div class="post-meta">
<i class="iconfont icon-tags"></i>
<a href="/tags/nodejs/" class="print-no-link">#nodejs</a>
<a href="/tags/backend/" class="print-no-link">#backend</a>
<a href="/tags/javascript/" class="print-no-link">#javascript</a>
<a href="/tags/npm/" class="print-no-link">#npm</a>
<a href="/tags/commonjs/" class="print-no-link">#commonjs</a>
<a href="/tags/esmodules/" class="print-no-link">#esmodules</a>
</div>
</div>
<div class="license-box my-3">
<div class="license-title">
<div>Node.js学习笔记</div>
<div>http://arkpln.github.io/447719203.html</div>
</div>
<div class="license-meta">
<div class="license-meta-item">
<div>Author</div>
<div>FangZhou</div>
</div>
<div class="license-meta-item license-meta-date">
<div>Posted on</div>
<div>July 2, 2025</div>
</div>
<div class="license-meta-item">
<div>Licensed under</div>
<div>
<a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/" rel="external nofollow noopener noreferrer">
<span class="hint--top hint--rounded" aria-label="BY - Attribution">
<i class="iconfont icon-cc-by"></i>
</span>
</a>
</div>
</div>
</div>
<div class="license-icon iconfont"></div>
</div>
<div style="width:100%;display:flex;justify-content:center;margin-bottom:1.5rem"><ins class="adsbygoogle" style="display:flex;justify-content:center;max-width:845px;width:100%;height:90px" data-ad-client="ca-pub-3240358922862141" data-ad-slot="6522434837"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script></div>
<div class="post-prevnext my-3">
<article class="post-prev col-6">
<a href="/391860339.html" title="Nestjs学习笔记">
<i class="iconfont icon-arrowleft"></i>
<span class="hidden-mobile">Nestjs学习笔记</span>
<span class="visible-mobile">Previous</span>
</a>
</article>
<article class="post-next col-6">
<a href="/1258387680.html" title="数据结构与算法">
<span class="hidden-mobile">数据结构与算法</span>
<span class="visible-mobile">Next</span>
<i class="iconfont icon-arrowright"></i>
</a>
</article>
</div>
</div>
<article id="comments" lazyload>
<div id="valine"></div>
<script type="text/javascript">
Fluid.utils.loadComments('#valine', function() {
Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
var options = Object.assign(
{"appId":"mEwkD7geCX7RWNO8srhDE2oP-gzGzoHsz","appKey":"4EF76hyiVA1QILHZThVbfoat","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"el":"#vcomments"},
{
el: "#valine",
path: window.location.pathname
}
)
new Valine(options);
Fluid.utils.waitElementVisible('#valine .vcontent', () => {
var imgSelector = '#valine .vcontent img:not(.vemoji)';
Fluid.plugins.imageCaption(imgSelector);
Fluid.plugins.fancyBox(imgSelector);
})
});
});
</script>
<noscript>Please enable JavaScript to view the comments</noscript>
</article>
</article>
</div>
</div>
</div>
<div class="side-col d-none d-lg-block col-lg-2">
<aside class="sidebar" style="margin-left: -1rem">
<div id="toc">
<p class="toc-header">
<i class="iconfont icon-list"></i>
<span>Table of Contents</span>
</p>
<div class="toc-body" id="toc-body"></div>
</div>
</aside>
</div>
</div>
</div>