我正在使用HAPI v17创建RESTful API。 我需要以下功能:
问题是我从函数uploadFile中得到一个空的返回值。在返回数组之前,如何等待迭代完成?
第二个问题:是否可以在不写入文件的情况下计算哈希值,然后使用createReadStream再次读取它?这样,我可以删除临时文件上传。
这是当前代码:
const uuidv4 = require('uuid/v4')
const Fs = require('fs')
const crypto = require('crypto')
const create = async function (request, reply) {
let files = uploadFile(request.payload['file'])
console.log(files)
let response = await models.document
.bulkCreate(
files
)
return response
}
function uploadFile (fileArr) {
let files = []
for (let i = 0; i < fileArr.length; i++) {
console.log('file ' + i)
let fileHash = uuidv4()
let fileExt = path.extname(fileArr[i].hapi.filename)
let file = fileArr[i]
let ws = Fs.createWriteStream('uploads/tmp_' + fileHash + fileExt)
file.pipe(ws)
ws.on('finish', function () {
Fs.createReadStream('uploads/tmp_' + fileHash + fileExt)
.pipe(crypto.createHash('sha1').setEncoding('hex'))
.on('finish', function () {
let hash = this.read()
Fs.rename('uploads/tmp_' + fileHash + fileExt, 'uploads/' + hash + fileExt, function (err) {
if (err) throw err
files.push({ hash: hash, path: hash + fileExt })
})
})
})
}
return files
}