fs.readFileSync Error Argument of type 'Buffer' is not assignable to parameter of type 'string'.ts(2345)

August 20, 2022

Header Suave man confused because of typescript
Photo by Bruce Mars on Unsplash

Reading data in node is relatively simple, however there are some small details to be aware of. Consider the following code below that reads a file and parses it into JSON.


  Some code...
// return type of string      // but fs.readFileSync returns type 'Buffer'
const jsonFile :string = fs.readFileSync(path.join(app.getPath('userData'), 'db', (arg.split('.')[0]+'.json')));
json = JSON.parse(jsonFile);

The node.js documentation here shows that readFileSync() returns string or Buffer and the functions signature is fs.readFileSync(path[, options]) .


The first argument means that fs.readFileSync() needs a path to the file being read. [, options] means there are a number of optional arguments that can go into the function. The options for this function include "encoding". It needs to be a string so the return type will be a string. 'utf-8' makes the most sense.


Below we add the following code:


  Some code...
const jsonFile :string = fs.readFileSync(path.join(app.getPath('userData'), 'db', (arg.split('.')[0]+'.json')), 'utf-8');
json = JSON.parse(jsonFile);

Now fs.readFileSync() will return a string and the error will be gone.