我正在使用下载文件的请求。我首先要检查状态码并仅在状态码为200时保存文件。它适用于我的二进制文件,但不适用于json文件(我有一个空文件)...
download(url, localPath, callback) {
if(fs.existsSync(localPath)) {
return setImmediate(callback, null)
}
const downloadStream = request.get(url);
downloadStream.on('error', err => callback(err));
downloadStream.on('response', response => {
if(200 === response.statusCode) {
return callback(`Status code ${response.statusCode} not expected`);
}
const fileStream = fs.createWriteStream(localPath);
fileStream.once('error', err => callback(err));
fileStream.once('finish', () => callback(null));
response.pipe(fileStream);
});
}
文件服务器是基本快递,使用sendFile
router.get('/api_path', (request, response) => {
const filePath = path.join('/my_folder/', 'my_file.json');
if(fs.existsSync(filePath)) {
console.log('GET file 200', filePath);
return response.sendFile(filePath, { headers: { 'content-type': 'application/octet-stream' } });
} else {
console.log('GET file 404', filePath);
return response.status(404).send({ code: "NOK", error: { message: 'File does not exist' } });
}
});
我注意到直接downloadStream
的管道传递适用于json文件,但是使用这种方法,我无法处理状态代码(因此,如果触发404错误,我的json文件将包含错误...)< / p>
有什么想法吗?