Async I/O and events · Lesson 6 of 18
Files and paths with fs/promises
Read and write safely, and build paths that work across operating systems.
node:fs/promises provides file-system APIs returning Promises. Specify an encoding such as utf8 or receive a Buffer. Use node:path rather than joining paths with / because Windows and Linux differ.
path.join builds a path
writeFile
OS filesystem
readFile + utf8
const fs = require("node:fs/promises")
const path = require("node:path")
async function main() {
const file = path.join("/tmp", "seacode-node-file.txt")
await fs.writeFile(file, "sea\ncode\n", "utf8")
const text = await fs.readFile(file, "utf8")
console.log(text.trim().split("\n").join(" + "))
await fs.unlink(file)
}
main().catch(console.error)Handle errors such as ENOENT according to meaning: optional configuration may use a default, but required data should fail clearly. For sensitive writes, write a temporary file then rename it to reduce partial-file risk if the process stops.
Quick question
What does readFile(file) return without an encoding?
Exercise
Write hello to /tmp/seacode-exercise.txt, read it uppercase, then delete it. Print HELLO.
Expected output: HELLO
const fs = require("node:fs/promises")
async function main() {
const file = "/tmp/seacode-exercise.txt"
}
main().catch(console.error)Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.