How to Use createWriteStream in Node.js for File Writing
In Node.js, use
fs.createWriteStream(path, options) to create a writable stream for a file. This lets you write data chunk by chunk efficiently, especially for large files or continuous data. You write data using the write() method and close the stream with end().Syntax
The createWriteStream function is part of Node.js's fs module. It creates a writable stream to a file.
path: The file path to write to (string orBuffer).options: Optional settings likeflags(e.g., 'w' for write),encoding(e.g., 'utf8'), andmode(file permission).
You use the returned stream's write() method to send data and end() to finish writing.
javascript
const fs = require('fs'); const writeStream = fs.createWriteStream('path/to/file', { encoding: 'utf8' }); writeStream.write('dataChunk'); writeStream.end();
Example
This example creates a write stream to a file named output.txt, writes two lines of text, and then closes the stream.
javascript
const fs = require('fs'); const writeStream = fs.createWriteStream('output.txt', { encoding: 'utf8' }); writeStream.write('Hello, this is the first line.\n'); writeStream.write('And this is the second line.\n'); writeStream.end(); writeStream.on('finish', () => { console.log('Writing completed successfully.'); });
Output
Writing completed successfully.
Common Pitfalls
Common mistakes include:
- Not calling
end()to close the stream, which can leave the file incomplete. - Ignoring errors by not listening to the
errorevent on the stream. - Writing data before the stream is ready or after it is closed.
Always handle errors and close the stream properly.
javascript
const fs = require('fs'); // Wrong: Not closing the stream const wrongStream = fs.createWriteStream('wrong.txt'); wrongStream.write('This will not be fully saved'); // Right: Handling errors and closing const rightStream = fs.createWriteStream('right.txt'); rightStream.on('error', (err) => { console.error('Error writing file:', err); }); rightStream.write('This will be saved properly.'); rightStream.end();
Quick Reference
Key points to remember when using createWriteStream:
- Use
write()to send data chunks. - Call
end()to finish writing and close the file. - Listen to
finishevent to know when writing is done. - Listen to
errorevent to catch problems. - Set encoding in options if writing strings.
Key Takeaways
Use fs.createWriteStream to write files efficiently in chunks.
Always call end() to close the stream and complete writing.
Listen to finish and error events to handle success and problems.
Set encoding option when writing text data.
Avoid writing after the stream is closed to prevent errors.