TypeError: fs.readFileSync is not a Function in JS [Solved]

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

# TypeError: fs.readFileSync is not a Function in JS

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.

fs readfilesync is not a function

Here's an example of how the error occurs.

index.js
// โ›”๏ธ fs.readFilesync is not a function // ๐Ÿ‘‡๏ธ method is misspelled, should be readFileSync const result = fs.readFilesync('example.txt', {encoding: 'utf-8'}); console.log(result);

# Using the readFileSync method in Node.js

To solve the error, import the fs module and call the readFileSync() method on it.

index.js
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.

example.txt
first line second line third line

using readfilesync in node js

# Using the older require() syntax to import readFileSync

Notice that we used the ES6 Modules import syntax. If you use an older version of Node.js, use the CommonJS require() syntax.

index.js
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.

shell
node index.js

Here's what the example.txt file looks like:

example.txt
Hello world ๐Ÿ‘‹ Another line ๐ŸŽ‰

If I run the index.js script with the node command, I get the following output.

readfilesync success

# Make sure to not try to use readFileSync on the browser

Note 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev