當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。