jwlu
jwlu

Reputation: 21

fs.createReadStream is undefined

So originally I was trying to use google cloud node client to do something. Then the error

Unhandled Rejection (TypeError): fs.createReadStream is not a function

keep showing up.

Here's the code snippet in "google-auth-library" that's been causing this

const fs = require("fs");
...
const filePath = path.resolve(this.keyFilename);
const stream = fs.createReadStream(filePath);
await this.fromStreamAsync(stream, this.clientOptions);

I tried to print out fs and fs.createReadStream, and it shows fs is an object and createReadStream is of type undefined.

const fs = require("fs");

console.log( "createReadStream type...");
console.log( typeof fs.createReadStream );

The node version is v12.13.1, and I am running a react app initialized by create-react-app on Chrome.

Can anyone tell me how to resolve this?

Upvotes: 2

Views: 4400

Answers (2)

Christophe Messaouik
Christophe Messaouik

Reputation: 78

If, like me, you encounter this problem while using

import fs from  'fs';

use the following instead

import * as fs from 'fs';

The issue you have is that fs doesn't have any default export which is what import fs from 'fs' will try to fetch.

What you want is to import named exports from fs which is what import * as fs from 'fs' will do.

Upvotes: 1

Nibrass H
Nibrass H

Reputation: 2497

You have to import all the libraries or modules and define filePath correctly.

Try the following code:

 var fs      = require('fs'),
 path    = require('path'),
 url     = require('url');

 var fileUrl = 'http://beta.business.applane.com/rest/file/download'+ '?token=5437bdb1811dfb0f03ec49a3&filekey=541bc4c909e41ce549567c07';

 var filename,
 filename = path.basename(url.parse(fileUrl).path);

 console.log(filename);
 const t = fs.createWriteStream(path.join(__dirname, filename));
 console.log(t)

Upvotes: 2

Related Questions