Search code examples
node.jsdownloadfssuperagent

nodejs download image with superangent ,check the file size


...
superagent
            .get(req.body.img)
            .set('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36')
            .pipe(fs.createWriteStream(filePath));
console.log(fs.statSync(filePath));
...

The output is {"dev":2049,"mode":33204,"nlink":1,"uid":1000,"gid":1000,"rdev":0,"blksize":4096,"ino":6578368,"size":0,"blocks":0,"atime":"2016-07-18T02:46:12.845Z","mtime":"2016-07-18T02:46:12.845Z","ctime":"2016-07-18T02:46:12.845Z","birthtime":"2016-07-18T02:46:12.845Z"}

why the file size is 0, i have check the file size with :

console.log(fs.statSync(filePath));

{ dev: 2049, mode: 33204, nlink: 1, uid: 1000, gid: 1000, rdev: 0, blksize: 4096, ino: 1975657, size: 1964074, blocks: 3840, atime: 2016-07-18T02:29:16.977Z, mtime: 2016-07-18T02:28:30.037Z, ctime: 2016-07-18T02:28:30.037Z, birthtime: 2016-07-18T02:28:30.037Z }


Solution

  • Perhaps, you call console.log while stream write to file. Try add listener on finish.

    var stream = fs.createWriteStream(filePath);
    stream.on('finish', function () {
        console.log(fs.statSync(filePath)); 
    });
    
    superagent 
        ...
        .pipe(stream);