writeFile
- Node.js course
- Beginner
- Lesson 102/116
- 5 min
Learn to write files with fs.writeFile.
Write with writeFile
fs.writeFile writes content to a file. If the file does not exist it is created; if it exists the content is overwritten. The operation is asynchronous, so you await it.
await fs.writeFile('out.txt', 'content');Here if out.txt does not exist it is created and 'content' is written. If it exists, the old content is fully replaced; to add to the end you need appendFile. When the write completes the Promise fulfils.
Creating files
writeFile creates the file automatically if it is missing. No separate creation step is needed; the first write creates both the file and the content. If the folder is missing you get an error; you must first create it with fs.mkdir.
await fs.writeFile('new.txt', 'first line');
// new.txt is created here if it was missingHere if new.txt does not exist it is created and 'first line' is written. If it already exists, the old content is fully replaced; to add to the end use the appendFile method.
Practice Your turn: create a file with writeFile
Start with import fs from 'fs/promises'. Define an async function run(). Inside, write await fs.writeFile('out.txt', 'hello file'). Log a message with console.log('written'). Call run().
Starter code
// Import fs/promises
// Define async function run
// Write with writeFile, log with console.log
// Call runSample solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('out.txt', 'hello file');
console.log('written');
}
run();Expected output
written
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: writeFile
await fs.____('out.txt', 'hello');
await fs.writeFile('out.txt', 'hello');
Explanation: writeFile writes to a file.
2 What happens when fs.writeFile is called on an existing file?
- Content is appended
- It throws an error
- Old content is replaced with the new Correct answer
- Nothing changes
Explanation: writeFile deletes old content and writes the new.
3 writeFile behaviours
| Term | Meaning |
|---|---|
writeFile |
writes to file |
missing |
creates it |
exists |
overwrites |