OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Node paths and text files

Use Node’s filesystem APIs and choose a write mode intentionally.

Lesson 19 of 25 · About 25 minutes · Beginner · English

By the end of this lesson

Create a practice text file without overwriting an existing file.

Before you start

  • Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
  • Complete lesson 18 or be comfortable with its examples.

Three words to know

Working directory
The folder from which relative data paths are resolved.
UTF-8
An encoding for storing text as bytes.
Exclusive creation
Creating a new file only when the path does not already exist.

1. Use a fresh practice folder

The .mjs example below runs in Node and creates notes.txt in the process’s current working folder. It is not relative to the source file merely because you placed them together. Keep this exercise separate from important files. Node APIs use node: imports; this source will not run as a browser script.

Create and read a small text fileJAVASCRIPT · Node.js · save as lesson.mjs
import { readFile, writeFile } from "node:fs/promises";

await writeFile("notes.txt", "Read\nTest\n", { encoding: "utf8", flag: "wx" });
const contents = await readFile("notes.txt", "utf8");
console.log(contents.trimEnd());
What you should see · example output
Read
Test

2. Preserve a useful failure

The wx flag requests exclusive creation, so a second run in the same folder fails instead of overwriting notes.txt. Inspect the first file, choose a fresh folder or intentionally choose a new name. The default write behaviour can replace content, so do not remove wx just to hide the error.

3. Convenience is not a bounded reader

readFile reads the full file and decoding with utf8 can replace malformed byte sequences. That is convenient for this small trusted practice text, not a strict untrusted-input validator. The final project performs a bounded byte read and uses a fatal TextDecoder instead. File permissions, slow storage and special files also need separate consideration.

YOUR TURN

A small check before you continue

Why does the second execution fail? Should you add a catch that prints an empty document?

Show a suggested answer

Exclusive creation rejects the existing path. An empty result would hide the real failure. Inspect the existing file and decide deliberately whether to keep it or choose another practice filename.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.