Get your own Node server
const fs = require('fs');
const path = require('path');

// Define the output file path
const outputFile = path.join(__dirname, 'writestream-example.txt');

// Create a WriteStream to write to the file
const writeStream = fs.createWriteStream(outputFile, {
  // Options
  flags: 'w',          // 'w' for write (overwrites existing file)
  encoding: 'utf8',    // Set the encoding for strings
  mode: 0o666,         // File mode (permissions)
  autoClose: true     // Automatically close the file descriptor when the stream ends
});

console.log('File WriteStream properties:');
console.log(`- Path: ${writeStream.path}`);
console.log(`- Pending: ${writeStream.pending}`);
console.log(`- High Water Mark: ${writeStream.writableHighWaterMark} bytes`);

// Handle stream events
writeStream.on('open', (fd) => {
  console.log(`File opened with descriptor: ${fd}`);
});

writeStream.on('ready', () => {
  console.log('WriteStream is ready');
  
  // Write data to the stream
  writeStream.write('First line of data.\n');
  writeStream.write('Second line of data.\n');
  writeStream.write('Third line of data.\n');
  
  // End the stream after writing all data
  writeStream.end('Final line of data.\n', () => {
    console.log('Finished writing to the file');
  });
});

// Handle drain event (when buffer is empty)
writeStream.on('drain', () => {
  console.log('Write buffer drained');
});

// Handle finish event (after end() and all data is flushed)
writeStream.on('finish', () => {
  console.log('All writes have been completed');
  console.log(`Total bytes written: ${writeStream.bytesWritten}`);
  
  // Read back the file contents to verify
  fs.readFile(outputFile, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file: ${err.message}`);
      return;
    }
    
    console.log('\nFile content:');
    console.log(data);
  });
});

writeStream.on('close', () => {
  console.log('Stream closed');
});

writeStream.on('error', (err) => {
  console.error(`Error: ${err.message}`);
});

              
File WriteStream properties:
- Path: /path/to/writestream-example.txt
- Pending: true
- High Water Mark: 16384 bytes
File opened with descriptor: 3
WriteStream is ready
Write buffer drained
Write buffer drained
Write buffer drained
Finished writing to the file
All writes have been completed
Total bytes written: 63

File content:
First line of data.
Second line of data.
Third line of data.
Final line of data.

Stream closed