mkdirp
npm i mkdirp -S // 1.0.4
明天在写上传文件时候,查看同步创立文件如是应用了 mkdirp 包, 不过发现网络有大部分谬误用法,起因是 mkdirp 的版本升级了更改了用法
网络谬误用法
const mkdirp = require('mkdirp');
await mkdirp(dir) // 谬误用法一
const mkdirp = require('mkdirp');
// 谬误用法二
mkdirp('./tmp/foo/bar/baz', function (err) {console.log(err);
});
正确写法
const mkdirp = require('mkdirp')
// 返回值是一个 Promise,解析为创立的一个目录
mkdirp('/tmp/foo/bar/baz').then(made =>
console.log(made)
)
const mkdirp = require('mkdirp')
// 返回目录 同步写法
const made = mkdirp.sync('/tmp/foo/bar/baz')
console.log(made)
应用实例
// 上传图片
async uploadImg() {const { ctx} = this
const parts = ctx.multipart({autoFields: true})
const urls = []
const dir = path.join(this.config.baseDir, 'app/public/upload/image/', dayjs().format('YYYY-MM-DD'))
await mkdirp.sync(dir)
let stream
while ((stream = await parts()) != null) {const fileType = stream.mimeType.split('/')[1]
const filename = dayjs().valueOf() + '.' + fileType || stream.filename.toLowerCase()
const target = path.join(dir, filename)
urls.push(`/public/upload/image/${filename}`)
const writeStream = await fs.createWriteStream(target)
await pump(stream, writeStream)
}
return urls[0]
}
// 上传文件
async uploadFile() {const { ctx} = this
const urls = []
const stream = await ctx.getFileStream()
const dir = path.join(this.config.baseDir, 'app/public/upload/file/', dayjs().format('YYYY-MM-DD'))
await mkdirp.sync(dir)
const fileType = stream.filename.toLowerCase().split('.')
const filename = dayjs().valueOf() + '.' + fileType[fileType.length - 1]
// 生成写入门路
const target = path.join(dir, filename)
const writeStream = await fs.createWriteStream(target) // 写入流
stream.pipe(writeStream) // 以管道形式写入流
await new Promise((resolve, reject) => {writeStream.on('finish', () => {
// 监听写入实现事件
urls.push(`/public/upload/file/${filename}`)
resolve(stream.fields)
})
writeStream.on('error', async (err) => {await sendToWormhole(stream) // 敞开管道
writeStream.destroy() // 销毁
reject(err)
})
})
return urls[0]
}
在线代码
GitHub 代码
调用该办法