📜  Node.js fs.createReadStream() 方法

📅  最后修改于: 2022-05-13 01:56:28.363000             🧑  作者: Mango

Node.js fs.createReadStream() 方法

createReadStream() 方法是 fs 模块的内置应用程序编程接口,允许您打开文件/流并读取其中存在的数据。
句法:

fs.createReadStream( path, options )

参数:此方法接受上面提到的两个参数,如下所述:

  • path:此参数保存要读取文件的文件的路径。它可以是字符串、缓冲区或 URL。
  • options:它是一个可选参数,包含字符串或对象。

返回值:此方法返回 fs.ReadStream 对象。
下面的示例说明了 Node.js 中的createReadStream() 方法
示例 1:

javascript
// Node.js program to demonstrate the 
// fs.createReadStream() method
   
// Include fs module
let fs = require('fs'),
  
// Use fs.createReadStream() method
// to read the file
reader = fs.createReadStream('input.txt');
  
// Read and display the file data on console
reader.on('data', function (chunk) {
    console.log(chunk.toString());
});


javascript
// Node.js program to demonstrate the 
// fs.createReadStream() method
   
// Include fs module
let fs = require('fs'),
  
// Use fs.createReadStream() method
// to read the file
reader = fs.createReadStream('input.txt', {
    flag: 'a+',
    encoding: 'UTF-8',
    start: 5,
    end: 64,
    highWaterMark: 16
});
  
// Read and display the file data on console
reader.on('data', function (chunk) {
    console.log(chunk);
});


输出:

input.txt file data:
GeeksforGeeks: A computer science portal for geeks

示例 2:

javascript

// Node.js program to demonstrate the 
// fs.createReadStream() method
   
// Include fs module
let fs = require('fs'),
  
// Use fs.createReadStream() method
// to read the file
reader = fs.createReadStream('input.txt', {
    flag: 'a+',
    encoding: 'UTF-8',
    start: 5,
    end: 64,
    highWaterMark: 16
});
  
// Read and display the file data on console
reader.on('data', function (chunk) {
    console.log(chunk);
});

输出:

forGeeks: A comp
uter science por
tal for geeks

参考: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options