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


node.js Stream writable.writable用法及代碼示例


writable.writable屬性是Stream模塊的內置應用程序編程接口,用於檢查writable.write()方法是否可以安全調用。

用法:

writable.writable 

返回值:如果可以安全地調用writable,則返回true。write()方法否則返回false。


以下示例說明了Node.js中writable.writable屬性的使用:

範例1:

// Node.js program to demonstrate the      
// writable.writable Property 
  
// Accessing stream module 
const stream = require('stream'); 
  
// Creating a stream and creating  
// a write function 
const writable = new stream.Writable({ 
  
  // Write function with its  
  // parameters 
  write:function(chunk, encoding, next) { 
  
    // Converting the chunk of 
    // data to string 
    console.log(chunk.toString()); 
    next(); 
  } 
}); 
  
// Writing data 
writable.write('hi'); 
  
// Again writing some data 
writable.write('GFG'); 
  
// Calling writable.writable 
// Property 
writable.writable;

輸出:

hi
GFG
true

範例2:

// Node.js program to demonstrate the      
// writable.writable Property 
  
// Accessing stream module 
const stream = require('stream'); 
  
// Creating a stream and creating  
// a write function 
const writable = new stream.Writable({ 
  
  // Write function with its  
  // parameters 
  write:function(chunk, encoding, next) { 
  
    // Converting the chunk of 
    // data to string 
    console.log(chunk.toString()); 
    next(); 
  } 
}); 
  
// Writing data 
writable.write('hi'); 
  
// Again writing some data 
writable.write('GFG'); 
  
// Calling end() method 
writable.end(); 
  
// Calling writable.writable 
// Property 
writable.writable;

輸出:

hi
GFG
false

在上麵的示例中,輸出為false,因為在調用writable.writable屬性之前調用了writable.end()方法,因此調用writable.write()方法並不安全,因此輸出為false。

參考: https://nodejs.org/api/stream.html#stream_writable_writable



相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Stream writable.writable Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。