Published on

How to Write String Content as File in Node.js

Authors

Here is how to write string content as a file in Node.js

import fs from 'fs/promises';

async function writeFileAsync(filePath, content) {
  try {
    await fs.writeFile(filePath, content, 'utf-8');
    console.log(`File "${filePath}" has been successfully written.`);
  } catch (error) {
    console.error(`Error writing to file "${filePath}": ${error.message}`);
  }
}


// Example usage
const filePath = 'path/to/file.txt'
const fileContent = 'Hello, this is me!';

await writeFileAsync(filePath, fileContent);

Happy writing-to files!