The fs (file system) module reads and writes files — something browser JavaScript is never allowed to do. It's one of the clearest examples of what makes Node.js different from JavaScript running in a page.
const fs = require('fs')
const data = fs.readFileSync('notes.txt', 'utf8')
console.log(data)The second argument, 'utf8', tells Node to return text instead of raw bytes. Leave it off and you get a Buffer — covered later in this course — instead of a readable string.
fs.writeFileSync('output.txt', 'Hello, file!')writeFileSync creates the file if it doesn't exist, and overwrites it completely if it does. To add to a file instead of replacing it, use fs.appendFileSync().
Every method ending in Sync blocks the program — nothing else runs until the file operation finishes. For a quick script that's fine. For a running server handling many requests at once, blocking on disk access stalls every other request too.
The non-blocking version takes a callback function instead of returning a value directly:
fs.readFile('notes.txt', 'utf8', (err, data) => {
if (err) {
console.error('Failed to read file:', err)
return
}
console.log(data)
})Node keeps running other code while the file is being read, and calls the function you passed in once it's done. This callback pattern — (err, result) as the first two parameters — shows up throughout Node's built-in APIs.
fs/promises gives the same non-blocking behavior with async/await instead of a callback:
const fs = require('fs/promises')
async function readNotes() {
const data = await fs.readFile('notes.txt', 'utf8')
console.log(data)
}
readNotes()| Style | How you call it | Blocks the program? |
|---|---|---|
fs.readFileSync() | Returns the value directly | Yes |
fs.readFile() | Takes a callback | No |
fs/promises's readFile() | awaitable | No |
Reach for the promise-based version by default in real code — it's non-blocking and reads cleanly with async/await. Sync methods are fine for one-off scripts and startup code that genuinely needs to finish before anything else runs.
if (fs.existsSync('config.json')) {
console.log('Found it')
}