//写文件
apiPost.writeFile = function (src, fileName, data) {
return new Promise((resolve, reject) => {
try {
//判断路径文件夹是否存在
fs.accessSync(src);
} catch (err) {
try {
//不存在创建文件夹
fs.mkdirSync(src)
} catch (error) {
//创建失败
reject(error)
}
}
//完整文件路径
let _cache_file = path.resolve(src, fileName);
//写文件
fs.writeFile(_cache_file, data, (err) => {
if (err) {
reject(err)
} else {
resolve(_cache_file)
}
});
});
}
//读文件
apiPost.readFile = function (src) {
return new Promise((resolve, reject) => {
let _cache_file = path.resolve(_cache_dir, src);
fs.readFileSync(_cache_file, {
encoding: 'utf-8'
}, function (err, bytesRead) {
if (err) reject(err);
resolve(bytesRead)
});
});
}
node fs读写文件(Promise封装)
最新推荐文章于 2024-06-07 12:07:18 发布