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.

JavascriptCli Tooling

Code

javascriptsnippet
14 lines
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 200

How 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/promises resolves 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

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.