I have a node.js function that should create a writeable stream wrapped with a Promise. The issue is that the promise returns pending
, because stream's finish
or error
event is not called which should resolve
or reject
the promise.
storeFile
async storeFile(file,path,types){
const { createReadStream, filename, mimetype } = await file
const stream = createReadStream();
var i = 0;
var f = filename.split(".");
var fName = "";
for(let j = 0; j < (f.length - 1);j++){
fName += f[j];
}
f = getSlug(fName,{lang:"sk"}) + ".jpg";
do {
if(i != 0){
f = Math.floor(Math.random() * 1000) + "_" + f;
}
i++;
}while (fs.existsSync(path + "/mala_" + f) || fs.existsSync(path + "/stredni_" + f) || fs.existsSync(path + "/velka_" + f) || fs.existsSync(path + "/maxi_" + f));
const resultPromise = new Promise((resolve, reject) =>
stream.on('error', error => {
console.log('error triggered', error);
if (stream.truncated)
fs.unlinkSync(path + "/" + f);
reject(error)
})
.pipe(fs.createWriteStream(path + "/" + f))
.on('error', error => {
console.log('error triggered', error);
reject(error);
})
.on('finish', () => {
console.log('finish triggered');
if(types){
var allPromises = [];
types.forEach(item => {
allPromises.push(this.resize(item,path,f));
});
if(allPromises.length > 0){
Promise.all(allPromises).then((values) => {
fs.unlinkSync(path + "/" + f);
resolve({file:f});
});
}else{
resolve({file:f});
}
}else{
resolve({file:f});
}
})
);
return resultPromise;
}
The issue was that I am using graphql-upload, which doesn't work well with new node.js version.