Reading 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: 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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat