- Published on
How to Write a Buffer as File in Node.js
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Node.js's built-in Buffer is an important module when working with a file system.
Here is how to write a buffer as a file in Node.js
import fs from 'fs/promises';
const filePath = 'path/to/file'
const bufferData = Buffer.from('Hello World', 'utf8');
// Promise-based code
fs.writeFile(filePath, bufferData)
.then(() => {
console.log('Buffer has been written to file successfully');
})
.catch((err) => {
console.error(err);
});
// Alternatively, with async/await
try {
await fs.writeFile(filePath, bufferData);
console.log('Buffer has been written to file successfully');
} catch (err) {
console.error(err);
}
Happy writing buffers!