Blog.

How to write a file in Node

Cover Image for How to write a file in Node

Using the native fs module, you can write content to a file, read and more.

TL;dr - Quick example

const fs = require("fs");

const fileName = "example.txt";
const content = "Hello world!"
const options = null

fs.writeFile(fileName, content, options, (error) => {
	if(error) {
		console.log(error)
		return
	}

	console.log("File was successfully created")
})

Node's File System

To create a file with Node.js, we can use the Node's file system module (it's built in Node, so we don't have to install it).

We have two options regarding importing fs module.

  1. Callback based (default)
  1. Promised based

I recommend using the promise based version mainly to avoid callback hell, but also for greater readability.

// Callback based
const fs = require("fs"); // using require
import fs from 'fs' // using es modules

// Promise based
const fs = require("fs").promises // using require
import fs from 'fs' // using es modules
const fsPromises = fs.promise

To create files with fs you can use the following methods:

  1. writeFile
  1. writeFileSync
  1. appendFile

The difference between writeFile and writeFileSync is the first is non-blocking and the second one is blocking (synchronous).

What does this mean?

Think about the following example:

fs.writeFile

const FILENAME = 'reports.txt'
const FILE_CONTENT = 'sales: 500'

fs.writeFile(FILENAME, FILE_CONTENT, null, (error) => {
  if(error) {
    console.log(error)
    return
  }

  console.log('Finished writing to file.')
})

fs.writeFileSync

fs.writeFileSync(FILENAME, FILE_CONTENT)

fs.appendFile

fs.appendFile(FILENAME, FILE_CONTENT, (err) => {
  if (error) {
		throw error
	}

  console.log('The "data to append" was appended to file!');
});

Handling errors

Promise based

💡
Wrapping writeFile method with a try catch block will let you handle errors easly.
const fs = require('fs').promises

async function writeReportToDisk(report) {
	const { name, extension, content } = report

	try {
		await fs.writeFile(`${name}${extension}`, content)

		console.log('File was successfully written to disk')
	} catch (error) {
		console.log(`Error writing file ${name} to disk`)
		throw error
	}
}

async function getReport() {
	try {
		const report = await fetch(...);
		
		if(report) {
			writeReportToDisk(report)
		}
	} catch (error) {
		console.log(error)
	}
}

getReports

Callback based

If, for some reason, you can't use the promise based fs methods, you can handle writing to disk errors in the callback provided to the fs.writeFile method.

const fs = require('fs')

function writeReportToDisk(report, callback) {
	const { name, extension, content } = report


	fs.writeFile(`${name}${extension}`, content, null, callback)
}

function getReport() {
	return fetch(...).then(report => {
		if (report) {
			writeReportToDisk(report, (error) => {
				if (error) {
					console.log(`Error writing file ${name} to disk`)
					throw error
				}
				
				console.log('File was successfully written to disk')		
			})
		}
	}
}

getReports

Daniel Turuș

@danielturus

Hi! My name is Daniel and I am a Full-stack JavaScript developer.

If you like my material, please consider following me on Twitter to get notified when new posts are published, ask me a question and stay in touch.