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
$ cat > message.txt <<'EOF' Alpha release notes Feature flag: enabled Owner: platform-team EOF
$ 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;
}
}
}
EOF
process.stdout.write() prints the file content without adding another newline or label around it.
$ node read-file.mjs message.txt Alpha release notes Feature flag: enabled Owner: platform-team
$ node read-file.mjs missing.txt Missing file: missing.txt
ENOENT is the Node.js error code for a path that does not exist.
$ echo $? 1
Run the status check before another shell command changes $?.
$ rm message.txt read-file.mjs