1
const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  resolve(bufferStream);
});

let policypath = 'pdfappl/' + submissionId + '_' + date + '_policydoc.pdf';
const resultpromise = <some api call giving .pdf file>;
let policybuf = Buffer.from(resultpromise, 'base64');
await createPolicyPackage(policypath, policybuf);

我正在使用带有上述代码的节点 v10.16.3 我能够创建一个文件,其中包含我从 pdfappl 文件夹中的 api 调用接收的数据,但之后尝试使用取消链接删除文件时。它没有删除它。也许它被标记为删除。bcoz 文件仅在节点进程运行之前可见。

一旦我终止节点进程,文件就会消失。

fs.unlink(file, function (err) {
 if (err) console.log("\n\n\n\n\n\n\nerr ", err)
});

也许 createWriteStream 没有完成写入过程。所以,我试着写它。

const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  wstream.on('close', ()=>{
    resolve(bufferStream);
  })
});

或者

const createPolicyPackage = (filePath, bufferStream) => new Promise(resolve => {
  let wstream = fs.createWriteStream(filePath);
  wstream.write(bufferStream);
  wstream.on('finish', ()=>{
    resolve(bufferStream);
  })
});

但是完成关闭事件没有触发,并且代码卡住了。如何正确关闭writeStream,以便在需要时删除文件

4

0 回答 0