Skip to content
the poor coder

nodejs write raw buffer to file

Poor Man
Published
Reading time
2 min read
On this page

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:

Text
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:

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC