Node.js
Append a line to a text file
Use appendFile to add text at the end of a file, creating the file if needed. Include the line separator explicitly; the API does not insert one for you.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const path = join(directory, "events.log");
await fs.appendFile(path, "started\n", "utf8");
await fs.appendFile(path, "finished\n", "utf8");
console.log((await fs.readFile(path, "utf8")).trimEnd());
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
The two awaited operations establish order within this script. Each call supplies one complete line, so reading the file produces started followed by finished. Append mode is useful for a small local event log or incremental report.
Limits and mistakes
A series of append calls across multiple processes is not a transaction or a general structured logging system. Consider rotation, permissions, and partial-write handling for long-running services. Do not store credentials or unnecessary personal data in logs.
Check the result
Expect two lines in the requested order. Include text without a newline in a disposable test to see how adjacent entries can merge accidentally.
Sources
Reference documentation for the behavior used in this guide: