Fix - fs.readFileSync is not a Function Error in JS


Borislav Hadzhiev

Tue Oct 19 20211 min read

Fix - fs.readFileSync is not a Function Error #

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.

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

To 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 example assumes that there is an example.txt file in the directory.

Notice that we used the ES6 Module import syntax. If you're using an older version of Node.js, you can use the Common JS syntax:

const fs = require('fs'); const result = fs.readFileSync('example.txt', {encoding: 'utf-8'}); console.log(result);

To run your node script, you can issue the node fileName.js command:

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 result back:

readfilesync success

Note that you can only use the fs module in Node.js and not in the browser.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee