gpt4 book ai didi

node.js - 下载并解压文件,然后检查内容,异步等待问题,node.js

转载 作者:太空宇宙 更新时间:2023-11-03 22:58:01 26 4
gpt4 key购买 nike

我正在下载 tar 格式的文件 request-promise模块。然后我使用 tar 解压该文件使用 async wait 语法的模块。

const list = new Promise(async (resolve, reject) => {
const filePath = "somedir/myFile.tar.gz";
if (!fs.existsSync(filePath)) {
const options = {
uri: "http://tarFileUrl",
encoding: "binary"
};

try {
console.log("download and untar");

const response = await rp.get(options);
const file = await fs.createWriteStream(filePath);
file.write(response, 'binary');
file.on('finish', () => {
console.log('wrote all data to file');
//here is the untar process
tar.x(
{
file: filePath,
cwd: "lists"
}
);
console.log("extracted");
});
file.end();
} catch(e) {
reject();
}
console.log("doesn't exist");
}
}

//here I am checking if the file exists no need to download either extract it (the try catch block)
//then the Array is created which includes the the list content line by line

if (fs.existsSync(filePath)) {
const file = await fs.readFileSync("lists/alreadyExtractedFile.list").toString().match(/[^\r\n]+/g);

if (file) {
file.map(name => {
if (name === checkingName) {
blackListed = true;
return resolve(blackListed);
}
});
}
else {
console.log("err");
}
}

console.log 输出序列如下:

download and untar
file doesn't exist
UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '...lists/alreadyExtractedFile.list'
wrote all data to file
extracted

因此文件 lists/alreadyExtractedFile.list 在创建之前会被检查。我的猜测是我做了一些错误的 async wait 操作。正如 console.logs 指出的那样,第二个检查 block 在某种程度上早于文件创建和解压过程。
请帮助我找出我做错了什么。

最佳答案

你的问题就在这里

  const file = await fs.readFileSync("lists/alreadyExtractedFile.list").toString().match(/[^\r\n]+/g);

readFileSync 函数不会返回 promise ,因此您不应等待它:

const file = fs.readFileSync("lists/alreadyExtractedFile.list")
.toString().match(/[^\r\n]+/g);

这应该可以解决问题

关于node.js - 下载并解压文件,然后检查内容,异步等待问题,node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com