自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一起來看看 Node.js v14.x LTS 中的這些新功能

系統(tǒng) Linux
在 2020 年 10 月 27 日 Node.js v14.15.0 LTS 版已發(fā)布,即長期支持版本,其中包含了很多很棒的新功能,以下內(nèi)容也是基于筆者在日常 Node.js 工作和學(xué)習(xí)中所總結(jié)的,可能不全,同時也歡迎補充,有些功能之前也曾單獨寫過文章來介紹,接下讓我們一起看看都有哪些新的變化?

 [[379658]]

作者簡介:五月君,Software Designer,公眾號「Nodejs技術(shù)?!棺髡?。

Node.js 是一個基于 Chrome V8 引擎的 JavaScript 運行時。在 2020 年 10 月 27 日 Node.js v14.15.0 LTS 版已發(fā)布,即長期支持版本,其中包含了很多很棒的新功能,以下內(nèi)容也是基于筆者在日常 Node.js 工作和學(xué)習(xí)中所總結(jié)的,可能不全,同時也歡迎補充,有些功能之前也曾單獨寫過文章來介紹,接下讓我們一起看看都有哪些新的變化?

目錄

  • Optional Chaining(可選鏈)
  • Nullish Coalescing(空值合并)
  • Intl.DisplayNames(國際化顯示名稱)
  • Intl.DateTimeFormat(國際化處理日期時間格式)
  • String.prototype.matchAll (throws on non-global regex)
  • Async Local Storage(異步本地存儲)
  • ES Modules 支持
  • Top-Level Await(頂級 await 支持)
  • Diagnostic report(診斷報告)
  • Stream
  • 使用異步迭代器

Optional Chaining(可選鏈)

如果我們使用 JavaScript 不管是用在前端或者 Node.js 服務(wù)端都會出現(xiàn)如下情況,因為我們有時是不確定 user 對象是否存在,又或者 user 對象里面的 address 是否存在,如果不這樣判斷, 可能會得到類似于 Cannot read property 'xxx' of undefined 這樣的類似錯誤。

  1. const user = { 
  2.   name'Tom'
  3.   address: { 
  4.     city: 'ZhengZhou' 
  5.   } 
  6. if (user && user.address) { 
  7.   console.log(user.address.city) 

現(xiàn)在我們有一種優(yōu)雅的寫法 "可選鏈操作符",不必明確的驗證鏈中的每個引用是否有效,以符號 "?." 表示,在引用為 null 或 undefined 時不會報錯,會發(fā)生短路返回 undefined。

  1. user.address?.city 
  2. user.address?.city?.length 
  3.  
  4. // 結(jié)合 ?.[] 的方式訪問相當(dāng)于 user.address['city'
  5. user.address?.['city'
  6.  
  7. // 結(jié)合 delete 語句使用,僅在 user.address.city 存在才刪除 
  8. delete user.address?.city 

參考 v8.dev/features/optional-chaining[1]

Nullish Coalescing(空值合并)

邏輯或操作符(||)會在左側(cè)為假值時返回右側(cè)的操作符,例如我們傳入一個屬性為 enabled:0 我們期望輸出左側(cè)的值,則是不行的。

  1. function Component(props) { 
  2.   const enable = props.enabled || true; // true 
  3. Component({ enabled: 0 }) 

現(xiàn)在我們可以使用 **空值合并操作符(??)**來實現(xiàn),僅當(dāng)左側(cè)為 undefined 或 null 時才返回右側(cè)的值。

  1. function Component(props) { 
  2.   const enable = props.enabled ?? true; // 0 
  3.  
  4. Component({ enabled: 0 }) 

參考:v8.dev/features/nullish-coalescing[2]

Intl.DisplayNames

對于國際化應(yīng)用需要用到的語言、區(qū)域、貨幣、腳本的名稱,現(xiàn)在 JavaScript 開發(fā)者可以使用 Intl.DisplayNames API 直接訪問這些翻譯,使應(yīng)用程序更輕松的顯示本地化名稱。

Language(語言)

  1. let longLanguageNames = new Intl.DisplayNames(['zh-CN'], { type: 'language' }); 
  2. longLanguageNames.of('en-US'); // 美國英語 
  3. longLanguageNames.of('zh-CN'); // 中文(中國) 
  4.  
  5. longLanguageNames = new Intl.DisplayNames(['en'], { type: 'language' }); 
  6. longLanguageNames.of('en-US'); // American English 
  7. longLanguageNames.of('zh-CN'); // Chinese (China) 

Region(區(qū)域)

  1. let regionNames = new Intl.DisplayNames(['zh-CN'], {type: 'region'}); 
  2. regionNames.of('US'); // 美國 
  3. regionNames.of('419'); // 拉丁美洲 
  4.  
  5. regionNames = new Intl.DisplayNames(['en'], {type: 'region'}); 
  6. regionNames.of('US'); // United States 
  7. regionNames.of('419'); // Latin America 

Currency(貨幣)

  1. let currencyNames = new Intl.DisplayNames(['zh-CN'], {type: 'currency'}); 
  2. currencyNames.of('CNY'); // 人民幣 
  3. currencyNames.of('USD'); // 美元 
  4.  
  5. currencyNames = new Intl.DisplayNames(['en'], {type: 'currency'}); 
  6. currencyNames.of('CNY'); // Chinese Yuan 
  7. currencyNames.of('USD'); // US Dollar 

Script(腳本)

  1. let scriptNames = new Intl.DisplayNames(['zh-CN'], {type: 'script'}); 
  2. scriptNames.of('Hans'); // 簡體 
  3. scriptNames.of('Latn'); // 拉丁文 
  4.  
  5. scriptNames = new Intl.DisplayNames(['en'], {type: 'script'}); 
  6. scriptNames.of('Hans'); // Simplified 
  7. scriptNames.of('Latn'); // Latin 

參考:v8.dev/features/intl-displaynames[3] 上述實例用到的國家代號和 code 都可從參考地址獲取。

Intl.DateTimeFormat

Intl.DateTimeFormat API 用來處理特定語言環(huán)境的日期格式。

  1. const date = new Date(); 
  2.  
  3. // Sunday, January 10, 2021 at 9:02:29 PM GMT+8 
  4. new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long'}).format(date
  5.  
  6. // 21/1/10 中國標(biāo)準(zhǔn)時間 下午9:02:29.315 
  7. new Intl.DateTimeFormat('zh-CN', { 
  8.   year'2-digit'
  9.   month'numeric'
  10.   day'numeric'
  11.   hour'numeric'
  12.   minute'numeric'
  13.   second'numeric'
  14.   fractionalSecondDigits: 3, 
  15.   timeZoneName: 'long' 
  16. }).format(date

參考: Intl/DateTimeFormat[4]

String.prototype.matchAll

matchAll() 返回一個包含所有匹配正則表達(dá)式的結(jié)果,返回值為一個不可重用(不可重用意思為讀取完之后需要再次獲取)的迭代器。

matchAll() 方法在 Node.js v12.4.0 以上版本已支持,該方法有個限制,如果設(shè)置的正則表達(dá)式?jīng)]有包含全局模式 g ,在 Node.js v14.5.0 之后的版本如果沒有提供會拋出一個 TypeError 異常。

  1. // const regexp = RegExp('foo[a-z]*','g'); // 正確 
  2. const regexp = RegExp('foo[a-z]*'); // 錯誤,沒有加全局模式 
  3. const str = 'table football, foosball, fo'
  4. const matches = str.matchAll(regexp); // TypeError: String.prototype.matchAll called with a non-global RegExp argument 
  5.  
  6. for (const item of matches) { 
  7.   console.log(item); 

參考:ES2020-features-String-prototype-matchAll-throws-on-non-global-regex[5]

AsyncLocalStorage

Node.js Async Hooks 模塊提供了 API 用來追蹤 Node.js 程序中異步資源的聲明周期,在最新的 v14.x LTS 版本中新增加了一個 AsyncLocalStorage 類可以方便實現(xiàn)上下文本地存儲,在異步調(diào)用之間共享數(shù)據(jù),對于實現(xiàn)日志鏈路追蹤場景很有用。

下面是一個 HTTP 請求的簡單示例,模擬了異步處理,并且在日志輸出時去追蹤存儲的 id。

  1. const http = require('http'); 
  2. const { AsyncLocalStorage } = require('async_hooks'); 
  3. const asyncLocalStorage = new AsyncLocalStorage(); 
  4. function logWithId(msg) { 
  5.   const id = asyncLocalStorage.getStore(); 
  6.   console.log(`${id !== undefined ? id : '-'}:`, msg); 
  7. let idSeq = 0; 
  8. http.createServer((req, res) => { 
  9.   asyncLocalStorage.run(idSeq++, () => { 
  10.     logWithId('start'); 
  11.     setImmediate(() => { 
  12.       logWithId('processing...'); 
  13.       setTimeout(() => { 
  14.         logWithId('finish'); 
  15.         res.end(); 
  16.       }, 2000) 
  17.     }); 
  18.   }); 
  19. }).listen(8080); 

下面是運行結(jié)果,我在第一次調(diào)用之后直接調(diào)用了第二次,可以看到我們存儲的 id 信息與我們的日志一起成功的打印了出來。

image.png

便利性的同時也會犧牲一些性能上的代價,關(guān)于 AsyncLocalStorage 的詳細(xì)使用介紹參見筆者的另一篇文章 “在 Node.js 中使用 async hooks 模塊的 AsyncLocalStorage 類處理請求上下文” 中的介紹。

ES Modules 支持

ES Modules 的支持總體上來說是個好事,進(jìn)一步的規(guī)范了 Node.js 與瀏覽器的模塊生態(tài),使之進(jìn)一步趨同,同時避免了進(jìn)一步的分裂。

在當(dāng)前 Node.js v14.x LTS 版本中已移除試驗性支持,現(xiàn)在使用無需使用標(biāo)志了,它使用 import、export 關(guān)鍵字,兩種使用方式:

使用 .mjs 擴展名

  1. // caculator.mjs 
  2. export function add (a, b) { 
  3.   return a + b; 
  4. }; 
  5.  
  6. // index.mjs 
  7. import { add } from './caculator.js'
  8.  
  9. console.log(add(4, 2)); // 6 

告訴 Node.js 將 JavaScript 代碼視為 ES Modules

默認(rèn)情況下 Node.js 將 JavaScript 代碼視為 CommonJS 規(guī)范,所以我們要在上面使用擴展名為 .mjs 的方式來聲明,除此之外我們還可以在 package.json 文件中 設(shè)置 type 字段為 module 或在運行 node 時加上標(biāo)志 --input-type=module 告訴 Node.js 將 JavaScript 代碼視為 ES Modules。

  1. // package.json 
  2.   "name""esm-project"
  3.   "type""module"
  4.   ... 

前端的同學(xué)可能會對以上使用 ES Modules 的方式很熟悉。

Top-Level Await

頂級 await 支持在異步函數(shù)之外使用 await 關(guān)鍵字,在 Node.js v14.x LTS 版本中已去掉試驗性支持,現(xiàn)在使用也不再需要設(shè)置標(biāo)志。

  1. import fetch from 'node-fetch'
  2. const res = await fetch(url) 

也可以像調(diào)用函數(shù)一樣動態(tài)的導(dǎo)入模塊。

  1. const myModule = await import('./my-module.js'); 

對于異步資源,之前我們必須在 async 函數(shù)內(nèi)才可使用 await,這對一些在文件頂部需要實例化的資源可能會不 好操作,現(xiàn)在有了頂級 await 我們可以方便的在文件頂部對這些異步資源做一些初始化操作。

詳細(xì)使用參見筆者在文章 “Nodejs v14.3.0 發(fā)布支持頂級 Await 和 REPL 增強功能” 中的介紹。

Diagnostic report(診斷報告)

Diagnostic report 是 Node.js v14.x LTS 提供的一個穩(wěn)定功能,在某些情況下會生成一個 JSON 格式的診斷報告,可用于開發(fā)、測試、生產(chǎn)環(huán)境。報告會提供有價值的信息,包括:JavaScript 和本機堆棧信息、堆統(tǒng)計信息、平臺信息、資源使用情況等,幫助用戶快速追蹤問題。

https://github.com/IBM/report-toolkit[6] 是 IBM 開發(fā)的一個款工具,用于簡化報告工具的使用,如下是一個簡單 Demo 它會造成服務(wù)的內(nèi)存泄漏。

  1. const total = []; 
  2. setInterval(function() { 
  3.   total.push(new Array(20 * 1024 * 1024)); // 大內(nèi)存占用,不會被釋放 
  4. }, 1000) 

最終生成的 JSON 報告被 report-toolkit 工具診斷的結(jié)果可能是下面這樣的。

image.png

詳細(xì)使用參見筆者在文章 “在 Node.js 中使用診斷報告快速追蹤問題” 中的介紹。

Stream

新版本中包含了對 Stream 的一些更改,旨在提高 Stream API 的一致性,以消除歧義并簡化 Node.js 核心各個部分的行為,例如:

  • http.OutgoingMessage 與 stream.Writable 類似
  • net.Socket 的行為與 stream.Duplex 完全相同
  • 一個顯著的變化 autoDestroy 的默認(rèn)值為 true,使流在結(jié)束之后始終調(diào)用 _destroy

參考:Node.js version 14 available now#Stream [7]

使用異步迭代器

使用異步迭代器我們可以對 Node.js 中的事件、Stream 亦或者 MongoDB 返回數(shù)據(jù)遍歷,這是一件很有意思的事情,盡管它不是 Node.js v14.x 中新提出的功能,例如 event.on 是在 Node.js v12.16.0 才支持的,這些目前看到的介紹還不太多,因此我想在這里做下簡單介紹。

在 Events 中使用

Node.js v12.16.0 中新增了 events.on(emitter, eventName) 方法,返回一個迭代 eventName 事件的異步迭代器,例如啟動一個 Node.js 服務(wù)可以如下這樣寫,想知道它的原理的可以看筆者下面提到的相關(guān)文章介紹。

  1. import { createServer as server } from 'http'
  2. import { on } from 'events'
  3. const ee = on(server().listen(3000), 'request'); 
  4. for await (const [{ url }, res] of ee) 
  5.   if (url === '/hello'
  6.     res.end('Hello Node.js!'); 
  7.   else 
  8.     res.end('OK!'); 

在 Stream 中使用

以往我們可以通過 on('data') 以事件監(jiān)聽的方式讀取數(shù)據(jù),通過異步迭代器可以一種更簡單的方式實現(xiàn)。

  1. async function readText(readable) { 
  2.   let data = ''
  3.   for await (const chunk of readable) { 
  4.     data += chunk; 
  5.   } 
  6.   return data; 

目前在 JavaScript 中還沒有被默認(rèn)設(shè)定 [Symbol.asyncIterator] 屬性的內(nèi)建對象,在 Node.js 的一些模塊 Events、Stream 中是可使用的,另外你還可以用它來遍歷 MongoDB 的返回結(jié)果。

關(guān)于異步迭代器詳細(xì)使用參見筆者在文章 “探索異步迭代器在 Node.js 中的使用” 中的介紹。

參考資料

[1]v8.dev/features/optional-chaining: https://v8.dev/features/optional-chaining

[2]v8.dev/features/nullish-coalescing: https://v8.dev/features/nullish-coalescing

[3]v8.dev/features/intl-displaynames: https://v8.dev/features/intl-displaynames

[4]Intl/DateTimeFormat: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

[5]ES2020-features-String-prototype-matchAll-throws-on-non-global-regex: https://node.green/#ES2020-features-String-prototype-matchAll-throws-on-non-global-regex

[6]https://github.com/IBM/report-toolkit: https://github.com/IBM/report-toolkit

[7]Node.js version 14 available now#Stream : https://nodejs.medium.com/node-js-version-14-available-now-8170d384567e

本文轉(zhuǎn)載自微信公眾號「Nodejs技術(shù)棧」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Nodejs技術(shù)棧公眾號。

 

責(zé)任編輯:武曉燕 來源: Nodejs技術(shù)棧
相關(guān)推薦

2021-10-26 06:43:36

NodeJavaScript引擎

2021-09-09 08:47:52

Dependency 安全漏洞工具

2023-10-20 10:11:00

Nuxt 3.8前端

2024-04-23 10:29:44

SassCSS前端

2024-03-21 08:21:34

Java 22Java 語言開發(fā)工具包

2024-05-24 08:35:00

Angular 18版本更新

2021-10-11 08:21:23

@Valuespringspring框架

2022-03-18 08:16:51

微軟Windows 11

2023-06-20 06:44:14

Node.jsCPU 負(fù)載

2021-10-12 23:45:43

NodeJs事件

2010-05-10 17:21:26

Unix操作系統(tǒng)

2021-07-15 05:26:22

Windows 10操作系統(tǒng)微軟

2024-04-09 10:10:23

GridCSS網(wǎng)格

2020-11-05 09:27:48

JavaScript開發(fā)技術(shù)

2022-06-24 06:32:46

iOS 16Beta 2

2024-03-08 06:58:55

TypeScript類型縮小模塊解析

2023-10-18 10:10:29

Node.js 21前端

2021-05-14 05:20:45

Windows10操作系統(tǒng)微軟

2023-06-30 08:05:41

2024-11-18 08:58:26

點贊
收藏

51CTO技術(shù)棧公眾號