Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Reading Files | Section
Node.js Fundamentals

bookReading Files

Swipe to show menu

A file is simply a collection of data stored on your computer, such as a text document or an image. In Node.js, you use the built-in fs module to interact with files. This module provides functions that let you read, write, and manage files easily. To read the contents of a file, you can use either fs.readFile (asynchronous) or fs.readFileSync (synchronous). For straightforward scripts, fs.readFileSync is often easier to understand because it reads the file and returns its contents directly.

// Import the built-in 'fs' module
const fs = require('fs');

// Read the contents of 'notes.txt' synchronously
const content = fs.readFileSync('notes.txt', 'utf8');

// Print the file content to the console
console.log(content);

When you use fs.readFileSync, you provide the filename and the encoding (usually "utf8" for text files). The function returns the file's content as a string, which you can then use in your program or print to the console. If the file exists and is readable, you will see its content displayed. However, if the file does not exist, Node.js will throw an error. This is a common situation you might encounter, especially if you mistype the filename or the file is missing.

Note
Note

Note: If the file you try to read does not exist, Node.js will throw an error like Error: ENOENT: no such file or directory. Always double-check your file paths and names.

Reading files with Node.js is direct and efficient using the fs module. You can quickly access and use file contents as strings in your applications, making it easy to process data stored outside your code.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 21

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 21
some-alt