Steven
Steven

Reputation: 158

fs.writeFileSync and then upload the file to Firebase Storage

I am able to create a 300 byte JavaScript file with fs.writeFileSync, and I can see the file contents with fs.readFileSync (in a console log at least) but I don't understand how to use this file any further to upload to Firebase Storage, it gives me an error saying "Exception from a finished function: Error: ENOENT: no such file or directory, stat '/widget-62a6e3d160781a477aea435c.js'"

I guess it is not in a directory because fs creates a file in a buffer? This is the code:

fs.writeFileSync(fileName, widgetContent);

console.log(fs.readFileSync(fileName, 'utf8'))




admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "gs://chatbot-eebb1.appspot.com"
});

var bucket = admin.storage().bucket();

//bucket.upload(fs.readFileSync(fileName, 'utf8'))
//bucket.upload(fileName)
bucket.upload(fs.createReadStream(fileName, { highWaterMark: 1024 }))

So then I also tried this:

bucket.upload(fs.createReadStream(fileName, { highWaterMark: 1024 }))

But got an error "Exception from a finished function: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of class_1 "

So anyway, when you use fs.writeFileSync where does the file go? To a buffer? If so, how would I access this file to upload it to Firebase Storage with their SDK?

Upvotes: 0

Views: 314

Answers (1)

samthecodingman
samthecodingman

Reputation: 26306

To start with, fs.writeFileSync, fs.readFileSync and fs.createReadStream are all reading/writing a file (named the value of fileName) in the code's current working directory.

Next, Bucket#upload() takes a filepath string as the first argument, not a stream. This is what is meant by The "path" argument must be of type string. Received an instance of class_1.

So to correct your call, you could use just bucket.upload(fileName) instead.

However, why not write widgetContent directly to Cloud Storage using File#save() instead of writing to disk and then uploading?

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "gs://chatbot-eebb1.appspot.com"
});

const bucket = admin.storage().bucket();

// make sure to return the Promise to the calling function
return bucket.file(fileName)
  .save(
    widgetContent, // this can be a string or byte array
    { public: true } // see https://googleapis.dev/nodejs/storage/latest/global.html#CreateWriteStreamOptions for options
  )
  .then(
    () => {
      // upload complete, do something
    },
    (err) => {
      // upload failed, do something
    }
  )

Upvotes: 1

Related Questions