
- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境設定
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥概念
- Node.js - 上傳檔案
- Node.js - 傳送郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTFul API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 從表中選擇資料
- Node.js - MySQL Where 條件
- Node.js - MySQL Order By 排序
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL 聯接
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新資料
- Node.js - MongoDB 限制結果
- Node.js - MongoDB 聯接
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
Node.js - Buffer.allocUnsafe() 方法
NodeJS 的 Buffer.allocUnsafe() 方法用於建立指定大小的新緩衝區。如果給定的大小大於 buffer.constants.MAX_LENGTH 或小於 0,則會丟擲型別為 ERR_INVALID_ARG_VALUE 的錯誤。如果給定的大小不是數字,則會丟擲 TypeError。
使用 buffer.allocUnsafe() 建立的緩衝區,分配的記憶體未初始化,其內容未知,即可能包含舊緩衝區的內容。也有可能包含敏感資料。出於安全考慮,最好使用 Buffer.alloc()。可以使用 Buffer.fill() 方法消除緩衝區中的舊資料。
語法
以下是 NodeJS Buffer.allocUnsafe() 方法 的語法:
Buffer.allocUnsafe(size)
引數
此方法接受一個引數。下面解釋了該引數。
size - 此引數為整數值,表示要建立的緩衝區的長度。
返回值
Buffer.allocUnsafe() 方法將返回一個指定大小的新緩衝區。
示例
此示例將使用 NodeJS Buffer.allocUnsafe() 方法建立一個緩衝區:
const buf = Buffer.allocUnsafe(5); console.log(buf);
輸出
緩衝區的大小為 5。執行上述程式將生成以下輸出:
<Buffer ff ff ff ff 39>
示例
此示例將使用 Buffer.allocUnsafe() 方法建立一個緩衝區,並使用 Buffer.fill() 方法填充緩衝區的值。
const buf = Buffer.allocUnsafe(5); buf.fill('a') console.log(buf);
輸出
緩衝區的大小為 5,我們已將緩衝區的內容填充為值:a。執行上述程式將生成以下輸出:
<Buffer 61 61 61 61 61>
示例
在此示例中,我們將看到如果使用的大小不是數字,則會丟擲錯誤。
const buf = Buffer.allocUnsafe('5'); buf.fill('a') console.log(buf);
輸出
由於使用的大小為字串,因此這是一個無效的值,因為大小必須為整數值。當您執行上述程式時,它將丟擲如下所示的錯誤。執行上述程式將生成以下輸出:
TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type string at Function.allocUnsafe (buffer.js:284:3) at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:1:20) at Module._compile (internal/modules/cjs/loader.js:816:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10) at Module.load (internal/modules/cjs/loader.js:685:32) at Function.Module._load (internal/modules/cjs/loader.js:620:12) at Function.Module.runMain (internal/modules/cjs/loader.js:877:12) at internal/main/run_main_module.js:21:11
nodejs_buffer_module.htm
廣告