我尝试在 writeStream 完成后 rename 文件名,promisify 了 rename 和 writeStream 并使用 async/await 来模拟同步,但遇到报错在 writeStream 完成后 rename 无法找到文件,但打印文件路径都能得到,请高手指点, 大致代码如下
async path => {
const tempPath = `${path}Temp`
//oldPath, 读取的文件
//makeRegex, 正则替换规则
//replaceFn, 替换函数
//replaceObj, 替换对象
await promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath})
console.log(fs.existsSync(tempPath)) // 输出 true
console.log(tempPath) // 输出路径正常
await promiseRename(tempPath, oldPath)
}
function promiseRename(oldPath, newPath) {
return new Promise((res, rej) => {
console.log(11111)
console.log(oldPath) // output static\projects\lotteryNine-40\index.htmlTemp
console.log(newPath) // output ./static/projects/lotteryNine-40/index.html
console.log(11111)
fs.rename(oldPath, newPath, (err) =>{
if(err) rej(err)
res()
})
})
}
function promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath}) {
return new Promise((res, rej) => {
const writable = fs.createWriteStream(tempPath)
fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(writable)
writable
.on('error', (err) => {rej(err)})
.on('finish', () => {res()})
})
}
报错信息为
Error: ENOENT: no such file or directory, open 'D:\dev\github\auto-activity\static\projects\lotteryNine-40\index.htmlTemp'
我很奇怪,既然能打印出文件路径为什么还会报找不到文件呢?