gpt4 book ai didi

node.js - 如果文件存在,则在 Nodejs 中移动文件,否则创建文件

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

我正在尝试将文件从位置 abc 移动到位置 xyz,如果该文件已存在于位置 xyz 中,请将其删除然后保存新的那一个。

这是我的代码

const promises = {
deleteFile: path => {
return new Promise((resolve, reject) => {
const fs = require('fs');

fs.stat(path, (err, stat) => {
if (err === null) {

fs.unlink(path, err => {
if (err) { return reject(err) }
resolve();
})
} else if(err.code == 'ENOENT') {
console.log('File does not exist');
resolve();
} else {
reject(err);
}
});
});
},
copyFile: (from, to) => {
return new Promise((resolve, reject)=> {
copyFile(from, to, (err) => {
if (err) { return reject(err); }
console.log(`Finished writing file ${to}`);
resolve();
})
})
}
}

const copyFile = (from, to, overallCb) => {
const fs = require('fs');
const rs = fs.createReadStream(from)
const ws = fs.createWriteStream(to)

let cbCalled = false;
function done (err) {
overallCb(err);
cbCalled = true;
}

rs.on('error', (err) => {
done(err);
})

ws.on('error', (err) => {
done(err);
})
rs.pipe(ws);
}
;

const OUTPUT_PATH = `./js/libs/`
, _NODE_MODULES = './node_modules/'
, filePath = `${_NODE_MODULES}somePathToAFile`
;

promises.deleteFile(`${OUTPUT_PATH}someFile.min.js`)
.then(promises.copyFile(filePath, `${OUTPUT_PATH}someFile.min.js`))
.then(words => {
console.log('**** done doing things ****');
})
.catch(error => { console.log(`ERROR`, error); })

如果文件存在,它只会删除该文件,不执行任何其他操作。

如果文件不存在,一切正常。

知道我做错了什么吗?

最佳答案

我的代码中有一些 promise 错误...对于 future 的我,这是上述代码的工作版本

'use strict';

const promises = {
deleteFile: path => {
return new Promise((resolve, reject) => {
const fs = require('fs');

fs.stat(path, (err, stat) => {
if (err === null) {

fs.unlink(path, err => {
if (err) { return reject(err) }
resolve(`Removing document at ${path}`);
})
} else if(err.code === 'ENOENT') {
resolve('File does not exist');
} else {
reject(err);
}
});
});
},
copyFile: (from, to) => {
return new Promise((resolve, reject) => {
copyFile(from, to, (err) => {
if (err) { return reject(err); }
resolve(`Finished writing file ${to}`);
})
})
}
}

const copyFile = (from, to, overallCb) => {
const fs = require('fs');
const rs = fs.createReadStream(from)
const ws = fs.createWriteStream(to)

let cbCalled = false;
function done (err) {
overallCb(err);
cbCalled = true;
}

rs.on('error', done)
ws.on('error', done)
.on('close', done)

rs.pipe(ws);
}
;

const OUTPUT_PATH = './js/libs/'
, _NODE_MODULES = './node_modules/'
, filePath = `${_NODE_MODULES}somePathToAFile`
;


promises.deleteFile(`${OUTPUT_PATH}someFile.min.js`)
.then(msg => {
console.log(msg)
return promises.copyFile(filePath, `${OUTPUT_PATH}someFile.js`)
})
.then(msg => {
console.log(msg)
})
.catch(err => { // Do errory things}

关于node.js - 如果文件存在,则在 Nodejs 中移动文件,否则创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232191/

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