我正在通过 nodejsrequest-promise
和request
库上传和下载文件(docx、pdf、文本等)。
问题request-promise
是他们没有从包中承诺pipe
方法。request
因此,我们需要以旧的方式来做。
我能够提出混合解决方案,我可以同时使用async/await
它Promise()
。这是示例:
/**
* Downloads the file.
* @param {string} fileId : File id to be downloaded.
* @param {string} downloadFileName : File name to be downloaded.
* @param {string} downloadLocation : File location where it will be downloaded.
* @param {number} version : [Optional] version of the file to be downloaded.
* @returns {string}: Downloaded file's absolute path.
*/
const getFile = async (fileId, downloadFileName, downloadLocation, version = undefined) => {
try {
const url = version ? `http://localhost:3000/files/${fileId}?version=${version}` :
`${config.dms.url}/files/${fileUuid}`;
const fileOutputPath = path.join(downloadLocation, fileName);
const options = {
method: 'GET',
url: url,
headers: {
'content-type': 'application/json',
},
resolveWithFullResponse: true
}
// Download the file and return the full downloaded file path.
const downloadedFilePath = writeTheFileIntoDirectory(options, fileOutputPath);
return downloadedFilePath;
} catch (error) {
console.log(error);
}
};
正如您在上面的getFile
方法中看到的,我们正在使用 ES 支持的最新async/await
功能进行异步编程。现在,让我们看看writeTheFileIntoDirectory
方法。
/**
* Makes REST API request and writes the file to the location provided.
* @param {object} options : Request option to make REST API request.
* @param {string} fileOutputPath : Downloaded file's absolute path.
*/
const writeTheFileIntoDirectory = (options, fileOutputPath) => {
return new Promise((resolve, reject) => {
// Get file downloaded.
const stream = fs.createWriteStream(fileOutputPath);
return request
.get(options.url, options, (err, res, body) => {
if (res.statusCode < 200 || res.statusCode >= 400) {
const bodyObj = JSON.parse(body);
const error = bodyObj.error;
error.statusCode = res.statusCode;
return reject(error);
}
})
.on('error', error => reject(error))
.pipe(stream)
.on('close', () => resolve(fileOutputPath));
});
}
nodejs 的美妙之处在于它支持不同异步实现的向后兼容。如果一个方法正在返回 Promise,那么await
将被踢入并等待该方法完成。
上述writeTheFileIntoDirectory
方法会下载文件并在流关闭成功时返回正向,否则返回错误。