# 流式操作
# 流式操作
一種是 buffer 模式,一種是 stream 模式,buffer 模式就是取完數據一次性操作,stream 模式就是邊取數據邊操作。**原來的方式在處理數據量較大的文件**時不能分塊處理,導致速度慢,內存容易爆滿。
## 讀取文件
~~~
const path = require('path');
const fs = require("fs");
let data = '';
// 創建可讀流
let readerStream = fs.createReadStream(path.join(__dirname, 'input.txt'));
// 設置編碼為 utf8。
readerStream.setEncoding('utf8');
// 處理流事件
// 有有數據可讀時觸發
readerStream.on('data', (chunk) => {
? ?data += chunk;
});
// 當沒有更多的數據可讀時觸發
readerStream.on('end', () => {
? ?console.log(data);
});
// 在讀取或寫入過程中發生錯誤時觸發
readerStream.on('error', (err) => {
? ?console.log(err.stack);
});
~~~
## 寫入文件
~~~
const path = require('path');
const fs = require("fs");
let data = '你好美,么么噠';
// 創建一個可以寫入的流,寫入到文件 output.txt 中
let writerStream = fs.createWriteStream(path.join(__dirname, 'output.txt'));
?
// 處理流事件
// 所有數據已被寫入到底層系統時觸發
writerStream.on('finish', () => {
? ?console.log("寫入完成。");
});
// 在讀取或寫入過程中發生錯誤時觸發
writerStream.on('error', (err) => {
? console.log(err.stack);
});
?
// 使用 utf8 編碼寫入數據
writerStream.write(data, 'utf8');
// 標記文件末尾,表明后面沒數據要再寫入了
writerStream.end();
~~~
- NodeJs
- 01-萬維網
- 02-CS 架構 VS BS 架構
- 03-Web 服務器訪問流程
- 04-url
- 05-網絡傳輸協議
- 06-HTTP 協議
- 07-報文
- 08-命令行界面
- 09-什么是 Node.js
- 10-環境安裝及配置
- 11-JavaScript 代碼運行環境
- 12-全局對象
- 13-Buffer
- 14-模塊化
- 15-EventEmitter
- 16-path模塊
- 17-流式操作
- 18-包
- 19-模板技術
- 20-ejs入門
- 21-express
- 01-什么是express
- 02-Hellow Express
- 03-靜態資源服務
- 04-路由
- 05-模塊化路由處理程序
- 06-中間件
- 07-手動實現中間件
- 08-常用內置中間件和第三方中間件
- 09-響應
- 10-獲取請求參數
- 11-Express 中使用模板引擎
- 22-web存儲與安全
- 01-cookie
- 02-sessionStorage
- 03-localStorage
- 04-base64
- 05-https
- 06-同源策略