请注意,fs的大部分函数回调只会返回一个error参数,所以只要判断error为false的情况下就返回成功,无论有没有第二个参数。
另外exists需要单独包装,因为第一个参数就代表返回内容
const fs = require('fs');
const ab = ['access', 'rename', 'ftruncate', 'chown', 'lchown', 'cmod', 'fchmod', 'stat', 'lstat', 'fstat', 'link', 'symlink',
'readlink', 'realpath', 'unlink', 'rmdir', 'readdir', 'close', 'open', 'utimes',
'futimes', 'fsync', 'write', 'read', 'readFile', 'writeFile', 'appendFile', 'mkdir', 'mkdtemp']
// fchown fdatasync mkdtemp rename truncate
ab.forEach(name => {
if (!fs[name])return;
exports[name] = (...n) => {
return new Promise((res, rej) => {
fs[name](...n, (er,d) => {
// 这里判断请注意不要去判断d参数
if (er) rej(er)
else res(d)
})
})
}
})
exports.exists = (path) => {
return new Promise((res, rej) => {
fs.exists(path, (exists) => {
res(exists);
})
});
}