我试图检查服务器上是否存在文件。如果没有,Node需要从指定的URL下载文件。以下是下载文件名,但文件大小为零(所以它没有正确下载)。我究竟做错了什么?
下载文件的代码位于catch块中。谢谢。
getApiDetails.then(
apiData => {
let imagesFolder = 'public/city_images/';
// Only do the following if the city was found by the pixarbay api. If a city wasn't found, we assign it to default.jpg
if (apiData.largeImageURL !== 'default.jpg') {
const imageFileExtension = apiData.largeImageURL.substring(apiData.largeImageURL.lastIndexOf('.')+1);
const imageFile = apiData.city+'.'+imageFileExtension;
// Check whether file exists, if not, download it
try {
if(fs.statSync(__dirname+'/'+imagesFolder+imageFile).isFile()){
// Rename the path so it can be accessed like a local file and not always fetched from 3rd party api server (hotlinking is a no no)
apiData.largeImageURL = imagesFolder+imageFile;
resolve(apiData);
}
}
catch(e) {
// apiData.largeImageURL is an online jpeg file
let file = fs.createWriteStream(__dirname+'/'+imagesFolder+imageFile); // The path to the file the stream is writing to
https.get(apiData.largeImageURL, function(response) {
response.pipe(file);
});
// Rename the path so it can be accessed like a local file and not always fetched from 3rd party api server (hotlinking is a no no)
apiData.largeImageURL = imagesFolder+imageFile;
resolve(apiData);
}
...