Sunday 26 April 2020

Help: Why is my image file not complete in this function? (fetching URL to writestream)

Heya. JS Noob here and I hope these type of questions are allowed. I appreciate and help/guidance on this. I've been pulling my hair out for days now on this.I am trying to upload an image from a URL to my Google Cloud Storage (Firebase). The following function shall return the file and a consecutive function will retrieve the actual Signed/Download Url to the new file. After all this I am updating a document in my Firestore Database with the new URL. That part works; the functions wait on uploading the (unfortunately incomplete) image and my document gets updated with the newly created file url. But the actual file/image is incomplete. :-(Here is what the Image actually looks like: https://imgur.com/a/KlYaPSRHere is my current iteration of my code, which I have changed, rewritten and went through trial and error.async function saveToStorage(fileUrl) { var storage = admin.storage(); var urlLib = require("url"); var pathLib = require("path"); //Get File Name from provided URL var parsed = urlLib.parse(fileUrl); var fileName = pathLib.basename(parsed.pathname); //Create Storage Reference with new File Name var bucket = storage.bucket('gs://myprojectname.appspot.com'); //Path Folder var folderPath = 'data/photos/'; //Path Folder + File var internalFilePath = folderPath + fileName ; //Bucket File Ref var file = bucket.file(internalFilePath); const request = require('request'); const writeStream = file.createWriteStream({ metadata: { contentType: 'image/jpg' } }); return new Promise((resolve, reject) => { request.get(fileUrl) .pipe(writeStream) .on("error", (err) => { console.error(`Error occurred`); reject(); }) .on('finish', () => { console.info(`Photo saved`); resolve(file); }); }); } I have tried using node-fetch and request and rewrote my function in several ways, but always turn out with this result. I'm sure it has something to do with how I use my Promise, because if I omit the Promise the file actually completes but then the main code keeps executing instead of waiting for this Promise.Thanks for any help!

Submitted April 26, 2020 at 06:05PM by Hagbard321

No comments:

Post a Comment