nodejs write raw buffer to file

How to Write Raw Buffer to File in Node.js

When working with Node.js, you might come across situations where you need to write raw buffer to a file. In this case, there are multiple ways to do it, and I will explain them below.

Method 1: Using fs.writeFile()

The simplest way to write a raw buffer to a file is by using the fs.writeFile() method from the built-in fs module in Node.js. Here's how you can do it:

const fs = require('fs');
const buffer = Buffer.from('hello world');
fs.writeFile('./file.txt', buffer, (err) => {
  if (err) {
    console.error('Error while writing to file');
    return;
  }
  console.log('File written successfully!');
});

This code creates a buffer from the string 'hello world', and then uses the fs.writeFile() method to write it to a file named 'file.txt' in the current directory. If there is no error, it will log 'File written successfully!' to the console.

Method 2: Using Node.js Streams

Another way to write raw buffer to a file is by using Node.js streams. Here's how you can do it:

const fs = require('fs');
const buffer = Buffer.from('hello world');
const writeStream = fs.createWriteStream('./file.txt');
writeStream.write(buffer);
writeStream.end();
writeStream.on('finish', () => {
  console.log('File written successfully!');
});

This code creates a buffer from the string 'hello world', and then creates a writable stream using the fs.createWriteStream() method. The buffer is then written to the stream using the write() method, and then the stream is closed using the end() method. Finally, the stream's 'finish' event is listened to, and when it fires, it logs 'File written successfully!' to the console.

Conclusion

Both of these methods are valid ways to write raw buffer to a file in Node.js. While the first method is simpler, the second method provides more control over how the data is written to the file. Choose the method that best fits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe