我试图在node.js中制作一个简单的程序,它可以在一定的时间间隔内下载相同的文件。如果下载的文件比前一个文件更新,那么它将在计数器的帮助下保存在一个新的文件名中。
如果它是一个新文件,那么我希望将它保存在last_unique.jpg名称中,并在下次下载该文件时使用它进行比较。但似乎不起作用。对于测试,我只是有一个空的last_unique.jpg,我希望它会被覆盖。但是从来没有,所以每次下载jpg文件时,它都是唯一的,并保存在file3.jpg、file3.jpg等文件中。
但是,输出看起来也可能是一些异步问题吗?它跳过前几次。
产出:
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!以下是代码:
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);发布于 2019-10-24 11:00:11
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请求的异步性质。
https://stackoverflow.com/questions/58538411
复制相似问题