Suggest an editImprove this articleRefine the answer for “How do you read a file in Node.js?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Four ways: `fs.readFile()` (callback-based, async), `fs/promises.readFile()` (the modern preferred option, via `await`), `fs.readFileSync()` (synchronous, blocks the thread), and `fs.createReadStream()` for very large files. **Key point:** for a server, always pick the async option - the synchronous one is only for CLI scripts or initialization.Shown above the full answer for quick recall.Answer (EN)Image## 1. Asynchronous reading (via a callback) Load the built-in `fs` module: ```javascript import fs from 'fs'; ``` And read the file: ```javascript fs.readFile('./data.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } console.log('File contents:', data); }); ``` - `'utf8'` gets you a string instead of a `Buffer`. - If the file isn't found, you get an `ENOENT` error. - This approach **doesn't block** the main thread (it's asynchronous). ## 2. Asynchronous reading with `fs/promises` (via `async/await`) The modern, concise, and preferred option. ```javascript import { readFile } from 'fs/promises'; try { const data = await readFile('./data.txt', 'utf8'); console.log('File contents:', data); } catch (err) { console.error('Error reading the file:', err); } ``` Advantages: - No callbacks, plays nicely with `async/await`; - The code reads "synchronously"; - A great fit for modern apps (Node 14+). ## 3. Synchronous reading (blocking) Sometimes handy at initialization (for example, loading configuration): ```javascript import fs from 'fs'; try { const data = fs.readFileSync('./config.json', 'utf8'); console.log('Configuration:', data); } catch (err) { console.error('Error:', err); } ``` But: - It **blocks** code execution until the file is read; - Not recommended on a server, only for CLI/initialization. ## 4. Streaming reads (for large files) If a file is very large (gigabytes), **streams** are the better choice, they read the file in pieces instead of all at once into memory. ```javascript import fs from 'fs'; const stream = fs.createReadStream('./bigfile.txt', 'utf8'); stream.on('data', chunk => { console.log('Got a chunk of data:', chunk); }); stream.on('end', () => { console.log('Reading finished!'); }); stream.on('error', err => { console.error('Error:', err); }); ``` Advantages: - Doesn't load the whole file into memory; - Data can be processed as it arrives; - Ideal for logs, streaming, HTTP responses. ## 5. Comparing the approaches | Approach | Method | Asynchronous | Use case | |---|---|---|---| | Callback | `fs.readFile()` | Yes | The basic, older style | | Promise | `fs/promises.readFile()` | Yes | The modern standard | | Synchronous | `fs.readFileSync()` | No | Short scripts only | | Stream | `fs.createReadStream()` | Yes | Large files | ## 6. Example: reading a JSON file ```javascript import { readFile } from 'fs/promises'; try { const raw = await readFile('./config.json', 'utf8'); const config = JSON.parse(raw); console.log('Config:', config); } catch (err) { console.error('Error reading JSON:', err); } ``` Node.js doesn't parse JSON automatically, `JSON.parse()` needs to be called. ## In one sentence > To read a file in Node.js, use `fs.readFile()` (asynchronously), `fs/promises.readFile()` (via `await`), or the `fs.createReadStream()` stream for large files.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.