如何复制外部图像(从XML流)在next运行时生成?



对于一个项目,我试图从远程源导入图像并将它们复制到我的static文件夹中(我不确定staticassets之间哪一个更好),因为我生成了我的路由,所以我可以在本地使用它们作为下一个构建过程的一部分。

所以在我的nuxt.config.js文件,我使用writeFileSync从节点fs库:

import fs from 'fs'
import path from 'path'
export default {
  // ...
  generate: {
    async routes() {
      const url = `https://via.placeholder.com/300/09f/fff.png`
      const dest = `${path.resolve(
        __dirname
      )}/static/images/fff.png`
      fs.writeFileSync(dest, url, 'ascii') // I also tried 'binary'
    }
  }

我没有得到错误,当我运行npm run generate,但图像是不可读的,重量只有几个字节。

阅读这些回复帮助我使它正常工作:

使用fs.writeFile保存图片

如何在下次构建期间访问远程数据并将其写入文件?

:

async routes() {
  const testUrl = `https://via.placeholder.com/300/09f/fff.png`
  const testDest = `${path.resolve(__dirname)}/static/images/fff.png`
  axios({
    method: 'get',
    url: testUrl,
    responseType: 'stream'
  }).then(function (response) {
    response.data.pipe(fs.createWriteStream(testDest))
  })
}

相关内容

最新更新