Using readFileSync after creating a file with createWriteStream shows empty buffer

十年热恋 提交于 2019-12-24 01:45:54

问题


I am using the gif-encoder npm module to create a gif, then the imgur-uploader module to upload it to imgur. Below is my relevant code, where pics is an array of filenames:

var gif = new GifEncoder(imageSize, imageSize);
var file = fs.createWriteStream('testing.gif');

gif.pipe(file);
gif.setRepeat(0);
gif.setQuality(20);
gif.setDelay(100);
gif.writeHeader();

var addToGif = function(images, counter = 0) {
    getPixels(images[counter], function(err, pixels) {
        gif.addFrame(pixels.data);
        gif.read();
        if (counter === images.length - 1) {
            gif.finish();
        } else {
            addToGif(images, ++counter);
        }
    })
}
addToGif(pics);

var sleep = require('sleep');
sleep.sleep(3) // I put this here because I thought I'd have to wait, but it doesn't work
console.log(fs.readFileSync('testing.gif'));
return imgurUploader(fs.readFileSync('testing.gif'), { title: 'Hello!' })
.then(data => {
    return data.link;
});

This does create the gif properly in my filesystem, but the console.log(fs.readFileSync('testing.gif') line just shows an empty <Buffer >! This means the imgurUploader function returns a 400 error since it's sending (what it thinks to be) an empty file.

If I replace the imgurUploader file argument with some pre-existing image in my folder, it works fine.

Why does readFileSync return an empty buffer when the file is indeed there?

来源:https://stackoverflow.com/questions/49656822/using-readfilesync-after-creating-a-file-with-createwritestream-shows-empty-buff

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!