nodejs fetch实现下载小文件

electron yekong

nodejs fetch实现小文件的保存

var getDown = async (downloadUrl, filePath, savePath) => {
    return new Promise((resolve) => {
        var url = filePathIsComplete(filePath, downloadUrl)
        fetch(url, {
            method: 'GET',
            headers: {'Content-Type': 'application/octet-stream'},
        }).then(res => res.buffer()).then(_ => {
            if (!fs.existsSync(savePath)) {
                fs.mkdirSync(savePath);
            }
            var filePath = getFileName(url)
            var filePathReName = GetRandomNum(1000, 10000) + getFileName(url)
            var filePaths = savePath + '/' + filePath
            var filePathReNames = savePath + '/' + filePathReName
            if (!fs.existsSync(filePaths)) {
                fs.writeFile(filePaths, _, "binary", function (err) {
                    if (err) console.error(err);
                    else console.log("下载成功");
                });
                resolve(filePath)
            } else {
                fs.writeFile(filePathReNames, _, "binary", function (err) {
                    if (err) console.error(err);
                    else console.log("下载成功");
                    const hash256Sync = createFileHash256Sync(filePaths)
                    const hash256Syncafter = createFileHash256Sync(filePathReNames)
                    if (hash256Sync === hash256Syncafter) {
                        fs.unlink(filePathReNames, (err, data) => {
                            if (err) {
                                console.log(err);
                            } else {
                                // console.log('');
                                resolve(filePath)
                            }
                        })
                    } else {
                        resolve(filePathReName)
                    }
                });
            }
        })
    })
}

使用实例

单页模板扒手 单页模板助手

喜欢