当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


node.js Stream readable.destroyed用法及代码示例


read.destroyed属性是Stream模块的内置应用程序编程接口,用于检查可读性。是否调用destroy()函数。

用法:

readable.destroyed

返回值:如果可读,则返回true.destroy()方法被调用,否则返回false。


以下示例说明了Node.js中read.destroyed属性的使用:

范例1:

// Node.js program to demonstrate the      
// readable.destroyed Property   
  
// Include fs module 
const fs = require("fs"); 
  
// Constructing readable stream 
const readable = fs.createReadStream("input.txt"); 
  
// Instructions for reading data 
readable.on('readable', () => { 
  let chunk; 
  
  // Using while loop and calling 
  // read method with parameter 
  while (null !== (chunk = readable.read())) { 
  
    // Displaying the chunk 
    console.log(`read:${chunk}`); 
  } 
}); 
  
// Handling error event 
readable.on('error', err => { 
    console.log(err); 
}); 
  
// Calling destroy method 
// with parameter 
readable.destroy('error'); 
  
// Displays that the stream is  
// destroyed 
console.log("Stream destroyed"); 
  
// Calling readable.destroyed 
// Property 
readable.destroyed;

输出:

Stream destroyed
true
error

范例2:

// Node.js program to demonstrate the      
// readable.destroyed Property   
  
// Include fs module 
const fs = require("fs"); 
  
// Constructing readable stream 
const readable = fs.createReadStream("input.txt"); 
  
// Instructions for reading data 
readable.on('readable', () => { 
  let chunk; 
  
  // Using while loop and calling 
  // read method with parameter 
  while (null !== (chunk = readable.read())) { 
  
    // Displaying the chunk 
    console.log(`read:${chunk}`); 
  } 
}); 
  
// Displays that the stream is  
// destroyed 
console.log("Program completed!!"); 
  
// Calling readable.destroyed 
// Property 
readable.destroyed;

输出:

Program completed!!
false
read:hello

因此,在read.destroyed属性之前不会调用read.destroy()方法,因此它返回false。

参考: https://nodejs.org/api/stream.html#stream_readable_destroyed



相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Node.js | Stream readable.destroyed Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。