Reading
Read text asynchronously
import { readFile } from 'node:fs/promises'
const text = await readFile('file.txt', 'utf8')
Reads a text file asynchronously. readFile returns a promise and avoids blocking the event loop. See fs.readFile.
Read text synchronously
import { readFileSync } from 'node:fs'
const buffer = readFileSync('file.txt')
const text = buffer.toString('utf8')
Reads a file synchronously. Use this only at startup or in scripts where blocking is acceptable. See fs.readFileSync.
Read JSON
import { readFile } from 'node:fs/promises'
const raw = await readFile('data.json', 'utf8')
const data = JSON.parse(raw)
Reads and parses JSON. Read the file as UTF-8, then hand the string to JSON.parse. See JSON.parse.
Stream lines
import { createReadStream } from 'node:fs'
import { createInterface } from 'node:readline'
const input = createReadStream('file.txt')
const lines = createInterface({ input })
for await (const line of lines) {
console.log(line)
}
Streams a file line by line. Use this for large files or logs instead of loading everything at once. See readline.
Related links
- Node.js fs (nodejs.org)
- Node.js readline (nodejs.org)
0 Comments for this cheatsheet. Write yours!