首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试在node.js循环中下载文件,但似乎遇到了一些同步问题

尝试在node.js循环中下载文件,但似乎遇到了一些同步问题
EN

Stack Overflow用户
提问于 2019-10-24 09:34:36
回答 1查看 165关注 0票数 0

我试图在node.js中制作一个简单的程序,它可以在一定的时间间隔内下载相同的文件。如果下载的文件比前一个文件更新,那么它将在计数器的帮助下保存在一个新的文件名中。

如果它是一个新文件,那么我希望将它保存在last_unique.jpg名称中,并在下次下载该文件时使用它进行比较。但似乎不起作用。对于测试,我只是有一个空的last_unique.jpg,我希望它会被覆盖。但是从来没有,所以每次下载jpg文件时,它都是唯一的,并保存在file3.jpg、file3.jpg等文件中。

但是,输出看起来也可能是一些异步问题吗?它跳过前几次。

产出:

代码语言:javascript
复制
downloading 1
downloading 2
downloading 3
Unique file spotted!
downloading 4
Unique file spotted!
downloading 5
Unique file spotted!
downloading 6
Unique file spotted!
downloading 7
Unique file spotted!
downloading 8
Unique file spotted!

以下是代码:

代码语言:javascript
复制
const http = require('http');
const fs = require('fs');
const md5File = require('md5-file');
const fileToDownload = "http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg";
var counter = 0;

function request() {
        counter = counter + 1
        console.log("downloading " + counter);
        const save = fs.createWriteStream("last_download.jpg");

        http.get(fileToDownload, function(response) {
                response.pipe(save)
        });

        const hash1 = md5File.sync('last_download.jpg');
        const hash2 = md5File.sync('last_unique.jpg');

        // it is a new file
        if (hash1.localeCompare(hash2) != 0) {
                console.log('Unique file spotted!');
                fs.copyFileSync('last_download.jpg','last_unique.jpg');
                fs.copyFileSync('last_unique.jpg','file' + counter + '.jpg');
        }
}

setInterval(request, 3000);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-24 11:00:11

代码语言:javascript
复制
const http = require('http');
const fs = require('fs');
const md5File = require('md5-file');
const fileToDownload = "http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg";
var counter = 0;

function request() {
    counter = counter + 1;
    console.log("downloading " + counter);
    const save = fs.createWriteStream("last_download.jpg");

    http.get(fileToDownload, function(response) {
        response.pipe(save);
        response.on('end',function () {
            save.end();

        })
    });


    save.on('finish',function () {

        const hash1 = md5File.sync('last_download.jpg');
        const hash2 = md5File.sync('last_unique.jpg');

        console.log(hash1,hash2);
        // it is a new file
        if (hash1.localeCompare(hash2) != 0) {
            console.log('Unique file spotted!');
            fs.copyFileSync('last_download.jpg','last_unique.jpg');
            fs.copyFileSync('last_unique.jpg','file' + counter + '.jpg');
        }

    });



}

setInterval(request, 3000);

您需要侦听流上的finish事件,否则可能是在流完全编写之前调用copy函数的情况。因此,将部分图像从last_download.jpg复制到last_unique.jpg,这意味着散列将有所不同。这是由于复制和http请求的异步性质。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58538411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档