How to write files in Node.js

Writing files is essential for data persistence, log generation, configuration management, and content creation in Node.js applications and automation scripts. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file writing in numerous Node.js build tools, documentation generators, and deployment scripts for CoreUI projects. From my expertise, the most reliable approach is to use the fs.writeFile() method for asynchronous file operations. This method prevents blocking the event loop while providing proper error handling and consistent performance in production applications.

Use fs.writeFile() method to asynchronously write content to files without blocking the event loop.

const fs = require('fs')
const content = 'Hello World'
fs.writeFile('output.txt', content, 'utf8', (err) => {
  if (err) throw err
  console.log('File saved successfully')
})

The fs.writeFile() method asynchronously writes data to a file, creating the file if it doesn’t exist or overwriting it if it does. The first parameter is the file path, the second is the content (string or buffer), the third specifies encoding (‘utf8’ for text files), and the fourth is a callback function for error handling. This non-blocking approach allows your application to continue processing other operations while file writing completes in the background.

Best Practice Note:

This is the same approach we use in CoreUI build processes for generating configuration files and documentation. For synchronous operations during startup, use fs.writeFileSync(), but prefer the async version for runtime operations. Use fs.promises.writeFile() with async/await for modern promise-based code without callbacks.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author