appendFile Appends And Creates Log Files
appendFile creates the file when missing and appends after that, so log lines never rewrite the whole file — missing parents must be handled.
Code
import { appendFile, readFile } from 'node:fs/promises';
// appendFile creates the file when missing and appends each call
await appendFile('app.log', 'boot: v1.0.0\n');
await appendFile('app.log', 'request: /health 200\n');
// Missing parent directories are not created — handle ENOENT yourself
await appendFile('logs/app.log', 'nope\n').catch(
(error) => console.log('missing dir:', error.code),
);
const content = await readFile('app.log', 'utf8');
console.log('lines:', content.trim().split('\n').length);
console.log(content.trimEnd());Output
Captured from a sandboxed run of this snippet in the build pipeline.
missing dir: ENOENT
lines: 32
boot: v1.0.0request: /health 200How the snippet works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:fs/promises, a Node.js built-in, exposing appendFile, readFile.
Top-level bindings content hold the demo state — nothing sits inside a function scope.
What to watch for
node:fs/promisesresolves inside Node.js without any package — it is a core module.
Using it
The run prints missing dir:, lines: — each prefix names the step that produced it.
Key statements
await appendFile('logs/app.log', 'nope\n').catch(
(error) => console.log('missing dir:', error.code),
);
await appendFile('app.log', 'request: /health 200\n');
const content = await readFile('app.log', 'utf8');
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does this import from outside the project?
- Only `node:fs/promises`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.