头图

mkdirp

npm i mkdirp -S // 1.0.4
Today, when I was writing and uploading files, I checked the synchronous creation of files and used the mkdirp package, but found that the network has most of the wrong usages. The reason is that the version of mkdirp has been upgraded and the usage has changed.

network error usage

const mkdirp = require('mkdirp');
await mkdirp(dir) //错误用法一
const mkdirp = require('mkdirp');
//错误用法二
mkdirp('./tmp/foo/bar/baz', function (err) {
  console.log(err); 
});

Correct spelling

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)

Example of use

// 上传图片
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]
    }

online code

GitHub code

call this method

image.png


羊先生
1.9k 声望821 粉丝