How to read a file in Node.js

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.

Steps to read a text file with Node.js:

  1. Create a text file for the read test.
    $ cat > message.txt <<'EOF'
    Alpha release notes
    Feature flag: enabled
    Owner: platform-team
    EOF
  2. 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;
        }
      }
    }
    EOF

    process.stdout.write() prints the file content without adding another newline or label around it.

  3. Run the reader against the text file.
    $ node read-file.mjs message.txt
    Alpha release notes
    Feature flag: enabled
    Owner: platform-team
  4. 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.

  5. Confirm the missing-file command returned a failure status.
    $ echo $?
    1

    Run the status check before another shell command changes $?.

  6. Remove the temporary files after the read behavior has been proven.
    $ rm message.txt read-file.mjs