确保某路径下存在某文件
我有个业务场景的需求,在某个操作前要确保存在某个路径下的某个文件,其实有fsextra库有现成的调用createFile或者ensureFile可以直接拿来用,其源码如下:
'use strict'const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const mkdir = require('../mkdirs')async function createFile (file) {let statstry {stats = await fs.stat(file)} catch { }if (stats && stats.isFile()) returnconst dir = path.dirname(file)let dirStats = nulltry {dirStats = await fs.stat(dir)} catch (err) {// if the directory doesn't exist, make itif (err.code === 'ENOENT') {await mkdir.mkdirs(dir)await fs.writeFile(file, '')return} else {throw err}}if (dirStats.isDirectory()) {await fs.writeFile(file, '')} else {// parent is not a directory// This is just to cause an internal ENOTDIR error to be thrownawait fs.readdir(dir)}
}function createFileSync (file) {let statstry {stats = fs.statSync(file)} catch { }if (stats && stats.isFile()) returnconst dir = path.dirname(file)try {if (!fs.statSync(dir).isDirectory()) {// parent is not a directory// This is just to cause an internal ENOTDIR error to be thrownfs.readdirSync(dir)}} catch (err) {// If the stat call above failed because the directory doesn't exist, create itif (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)else throw err}fs.writeFileSync(file, '')
}module.exports = {createFile: u(createFile),createFileSync
}
我看了下,感觉不太满意。用node.js自带的fs模块的话,要有好几步操作:检查文件状态,存在则返回,不存在的话,创建目录,创建空文件
function ensureFile(file) {return fs.promises.access(file).catch(e=>{return fs.promises.open(file, 'w').catch(e=>{ return fs.promises.mkdir(path.dirname(file), { recursive: true }).then(()=>{ return fs.promises.open(dest_path, 'w'); }); }).then(fd=>{ return fd.close(); });});}
另外关于创建空文件,虽然fs.writeFile(file,‘’)只需要一条语句,我打开和关闭文件需要两条语句,个人理解实际开销可能后者更小一些。