Small Node.js scripts often need local text from templates, release notes, or configuration files before the rest of the program can continue. Reading the file through the promise-based file-system API keeps the script asynchronous while still giving the caller a normal failure path when the input is missing.
The node:fs/promises module provides readFile() for promise-based file reads. Passing encoding: 'utf8' returns a string instead of a Buffer, which is the usual shape for text files that will be printed, parsed, or handed to another function.
The file reader takes a path from the command line, prints the text exactly as read from disk, and sets a nonzero exit status when the file is missing. Unexpected file-system errors remain visible because permission or directory failures are rethrown instead of being folded into the missing-file message.
Related: How to read a file stream in Node.js
Related: How to read a JSON file in Node.js
Related: How to write a file in Node.js
Steps to read a text file with Node.js:
- Create a text file for the read test.
$ cat > message.txt <<'EOF' Alpha release notes Feature flag: enabled Owner: platform-team EOF
- Save the file-reading script.
$ cat > read-file.mjs <<'EOF' import { readFile } from 'node:fs/promises'; import process from 'node:process'; const filePath = process.argv[2]; if (!filePath) { console.error('Usage: node read-file.mjs <file>'); process.exitCode = 1; } else { try { const content = await readFile(filePath, { encoding: 'utf8' }); process.stdout.write(content); } catch (error) { if (error.code === 'ENOENT') { console.error(`Missing file: ${filePath}`); process.exitCode = 1; } else { throw error; } } } EOFprocess.stdout.write() prints the file content without adding another newline or label around it.
- Run the reader against the text file.
$ node read-file.mjs message.txt Alpha release notes Feature flag: enabled Owner: platform-team
- Run the reader against a missing path.
$ node read-file.mjs missing.txt Missing file: missing.txt
ENOENT is the Node.js error code for a path that does not exist.
- Confirm the missing-file command returned a failure status.
$ echo $? 1
Run the status check before another shell command changes $?.
- Remove the temporary files after the read behavior has been proven.
$ rm message.txt read-file.mjs
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.