Last updated: Mar 2, 2024
Reading timeยท2 min

The "fs.readFileSync" is not a function error occurs when we misspell the
readFileSync method or try to use the method in the browser.
To solve the error, import fs from the fs package in a Node.js application
and call the readFileSync method on it.

Here's an example of how the error occurs.
// โ๏ธ fs.readFilesync is not a function // ๐๏ธ method is misspelled, should be readFileSync const result = fs.readFilesync('example.txt', {encoding: 'utf-8'}); console.log(result);
readFileSync method in Node.jsTo solve the error, import the fs module and call the
readFileSync()
method on it.
import * as fs from 'fs'; const result = fs.readFileSync('example.txt', { encoding: 'utf-8', }); console.log(result);
The code sample assumes that there is an example.txt file in the same
directory as your index.js file.
first line second line third line

readFileSyncNotice that we used the ES6 Modules import syntax. If you use an older version
of Node.js, use the CommonJS require() syntax.
const fs = require('fs'); const result = fs.readFileSync('example.txt', { encoding: 'utf-8', }); console.log(result);
Issue the node fileName.js command to run your Node.js script.
node index.js
Here's what the example.txt file looks like:
Hello world ๐ Another line ๐
If I run the index.js script with the node command, I get the following
output.

readFileSync on the browserNote that you can only use the fs module in Node.js.
The module cannot be used in the browser because reading the file system of the site's visitors is not permitted.
You can learn more about the related topics by checking out the following tutorials: