Skip to content

Instantly share code, notes, and snippets.

@noxify
Created February 9, 2020 13:09
Show Gist options
  • Save noxify/47ab5e41c61555080224cb906db1765f to your computer and use it in GitHub Desktop.
Save noxify/47ab5e41c61555080224cb906db1765f to your computer and use it in GitHub Desktop.
gridsome - download remote files
// /content/entries/entry1.md
---
title: First Post
excerpt: First Post
date: 2020-01-14T21:53:14.578Z
localImage: ./sumit-saharkar-d3_ssraccV8-unsplash.jpg
remoteImage: https://images.unsplash.com/photo-1580451998921-c1e6e1ababe0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80
---
Image Credits: https://unsplash.com/@sumit_saharkar
// /gridsome.config.js
module.exports = {
siteName: 'Gridsome',
plugins: [
{
use: '@gridsome/source-filesystem',
options: {
path: 'content/entries/*.md',
typeName: 'Entry',
remark: {
// remark options
}
}
},
{
use: '~/plugins/gridsome-plugin-image-download',
options: {
'typeName' : 'Entry',
'sourceField': 'remoteImage',
'targetField': 'imageDownloaded',
'targetPath': 'static'
}
}
],
}
// plugins/gridsome-plugin-image-download/gridsome.server.js
const got = require('got')
const crypto = require('crypto')
const hash = crypto.createHash('sha256')
const path = require('path')
const fs = require('fs')
const FileType = require('file-type')
module.exports = function (api, options) {
api.loadSource(({addSchemaTypes}) => {
console.log("##### ADD SCHEMA TYPE #####");
addSchemaTypes(`
type ${options.typeName} implements Node @infer {
${options.targetField}: Image
}
`)
})
api.loadSource(async actions => {
console.log("##### DOWNLOAD IMAGES #####");
var nodes = actions.getCollection(options.typeName);
nodes.data().forEach(async function(node) {
if(node[options.sourceField]) {
hash.update(node[options.sourceField]);
var newFileName = hash.digest('hex');
var localPath = await getRemoteImage(node[options.sourceField], options.targetPath, newFileName);
node[options.targetField] = localPath;
const newNode = nodes.updateNode(node);
}
})
})
}
async function getRemoteImage(sourceUrl, targetPath, targetFileName) {
const stream = got.stream.get(sourceUrl);
const fileType = await FileType.fromStream(stream);
const filePath = path.resolve('./', targetPath, `${targetFileName}.${fileType.ext}`)
stream
.on('response', function (res) {
res.pipe(fs.createWriteStream(filePath))
}).resume()
return filePath;
}
// plugins/gridsome-plugin-image-download/package.json
{
"name": "gridsome-plugin-image-download",
"version": "1.0.0",
"description": "",
"main": "gridsome.server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"got": "^10.5.5",
"file-type": "^14.1.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment