Writing to a file using writeFile or writeFileSync

suggest change
const fs = require('node:fs');

// Save the string "Hello world!" in a file called "hello.txt" in
// the directory "/tmp" using the default encoding (utf8).
// This operation will be completed in background and the callback
// will be called when it is either done or failed.
fs.writeFile('/tmp/hello.txt', 'Hello world!', err => {
  // If an error occurred, show it and return
  if(err) return console.error(err);
  // Successfully wrote to the file!
});

// Save binary data to a file called "binary.txt" in the current
// directory. Again, the operation will be completed in background.
const buffer = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
fs.writeFile('binary.txt', buffer, err => {
  // If an error occurred, show it and return
  if(err) return console.error(err);
  // Successfully wrote binary contents to the file!
});

The /tmp path in the first call is a Unix directory. On Windows that absolute path is on the current drive.

fs.writeFileSync behaves similarly to fs.writeFile, but does not take a callback as it completes synchronously and therefore blocks the main thread. Most node.js developers prefer the asynchronous variants, which return before the disk write finishes.

Note: Blocking the main thread is bad practice in node.js. Synchronous functions should only be used when debugging or when no other options are available. The next sample uses the fs binding from above.

// Write a string to another file and set the file mode to 0755
try {
  fs.writeFileSync('sync.txt', 'anni', { mode: 0o755 });
} catch(err) {
  // An error occurred
  console.error(err);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents