使用axios获取外部图像,然后将其保存到文件系统?

时间:2019-01-11 17:34:47

标签: node.js asynchronous axios node.js-stream

我有以下针对每个请求调用的函数。

async function checkForNewData() {
  var now = moment();
  var lastUpdateUnix = fs.readFileSync('.data/last-update.txt').toString();
  var lastUpdate = moment.duration(lastUpdateUnix, 'seconds');
  now.subtract(lastUpdate);
  if (now.hour() >= 1) {
    console.log("Last update is over 1 hour old. Getting new data.");
    // Schedule
    console.log("Getting new schedule.")
    let res = await axios.get('https://splatoon2.ink/data/schedules.json', { headers: { "User-Agent": "Splatoon2.ink caching server at glitch.com/~splatoon2-ink-cache" } });
    fs.writeFileSync('.data/rotations.json', JSON.stringify(res.data));
    // Image
    console.log("Getting new image.");
    let resImage = await axios.get('https://splatoon2.ink/twitter-images/schedule.png', { headers: { "User-Agent": "Splatoon2.ink caching server at glitch.com/~splatoon2-ink-cache" }, responseType: 'stream' });
    const path = Path.resolve(__dirname, '.data', 'image.png');
    const writer = fs.createWriteStream(path);
    resImage.data.pipe(writer);
    fs.writeFileSync('.data/last-update.txt', moment().unix());
    console.log("Data is now up to date.");
    return;
  }
}

在每条Express路线上,我都有类似的东西。

app.get('/', function(request, response) {
  console.log("Request for schedule.");
  checkForNewData().then(function() {
    console.log("Sending schedule.");
    response.sendFile(__dirname + '/.data/rotations.json');
  });
});

我的目标是运行该函数,该函数将检查当前数据是否过时(使用时刻库​​),如果是,则获取新数据。但是由于某种原因,当使用axios获取图像部分时,不会将其写入文件系统。我尝试使用不同的方法来保存它,但是我尝试过的所有方法都无法正常工作。

这是我的完整档案。

// server.js
// where your node app starts

// init project
const express = require('express');
const app = express();
const moment = require('moment');
const fs = require("fs");
const Path = require('path');
const axios = require("axios")
fs.writeFileSync('.data/last-update.txt', '0');
fs.writeFileSync('.data/rotations.json', '{}');
// we've started you off with Express, 
// but feel free to use whatever libs or frameworks you'd like through `package.json`.

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

async function checkForNewData() {
  var now = moment();
  var lastUpdateUnix = fs.readFileSync('.data/last-update.txt').toString();
  var lastUpdate = moment.duration(lastUpdateUnix, 'seconds');
  now.subtract(lastUpdate);
  if (now.hour() >= 1) {
    console.log("Last update is over 1 hour old. Getting new data.");
    // Schedule
    console.log("Getting new schedule.")
    let res = await axios.get('https://splatoon2.ink/data/schedules.json', { headers: { "User-Agent": "Splatoon2.ink caching server at glitch.com/~splatoon2-ink-cache" } });
    fs.writeFileSync('.data/rotations.json', JSON.stringify(res.data));
    // Image
    console.log("Getting new image.");
    let resImage = await axios.get('https://splatoon2.ink/twitter-images/schedule.png', { headers: { "User-Agent": "Splatoon2.ink caching server at glitch.com/~splatoon2-ink-cache" }, responseType: 'stream' });
    const path = Path.resolve(__dirname, '.data', 'image.png');
    const writer = fs.createWriteStream(path);
    resImage.data.pipe(writer);
    fs.writeFileSync('.data/last-update.txt', moment().unix());
    console.log("Data is now up to date.");
    return;
  }
}

// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
  console.log("Request for schedule.");
  checkForNewData().then(function() {
    console.log("Sending schedule.");
    response.sendFile(__dirname + '/.data/rotations.json');
  });
});

app.get('/image', function(request, response) {
  console.log("Request for image.");
  checkForNewData().then(function() {
    console.log("Sending image.");
    response.type('png');
    response.sendFile(__dirname + '/.data/image.png');
  });
});

// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' + listener.address().port);
});

0 个答案:

没有答案