-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreviewimages.js
More file actions
110 lines (102 loc) · 2.58 KB
/
previewimages.js
File metadata and controls
110 lines (102 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const axios = require("axios");
const puppeteer = require("puppeteer");
const fs = require("fs");
require("dotenv").config();
const settings = {
source: "https://www.d-hagemeier.com/preview-images.json",
domain: "https://www.d-hagemeier.com",
imgwidth: 1200,
imgheight: 628,
};
/**
* Helper for file existence
* @param {String} filePath - Path to check for existence
*/
function fileExist(filePath) {
return new Promise((resolve, reject) => {
fs.access(filePath, fs.F_OK, (err) => {
if (err) {
// File needs to be generated
return resolve(err);
}
reject("File exists");
});
});
}
/**
* Helper to create directory
* @param {String} dirPath - Path to directory
*/
function createDirectory(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath);
}
}
/**
* Start Puppeteer, check for file existence and pass files
* @param {Object} response - List of files to screenshot
*/
async function setupPuppeteer(response) {
try {
browser = await puppeteer.launch({ headless: true });
distDir = await createDirectory("public/cache");
var i;
for (i = 0; i < response.length; i++) {
let filename = response[i].filename;
let path = response[i].path;
let distUrl = "public/cache/" + filename + ".png";
let existFlag = await fileExist(distUrl);
if (existFlag) {
await getScreenshot(path, filename, distUrl);
}
}
} catch (err) {
console.log(err);
} finally {
browser.close();
}
}
/**
*
* @param {String} path - Path from source file
* @param {String} filename - Filename for screenshot
* @param {String} distUrl - Output URL
*/
async function getScreenshot(path, filename, distUrl) {
try {
page = await browser.newPage();
let srcUrl = settings.domain + path;
console.log("Getting: " + path);
await page.setViewport({
width: settings.imgwidth,
height: settings.imgheight,
});
await page.goto(srcUrl, { waitUntil: "networkidle0" });
await page.screenshot({ path: distUrl });
console.log("Got: " + filename + ".png");
} catch (err) {
console.error("Error getscreen:", err);
}
}
/**
* Setup Dummy directory for netlify
*/
function dummydist() {
createDirectory("public");
fs.writeFile("public/index.html", "", function (err) {
if (err) throw err;
console.log("Dummy dist created");
});
}
/**
* Start Axios to get and pass source file
*/
axios
.get(settings.source)
.then((response) => {
dummydist();
setupPuppeteer(response.data);
})
.catch((err) => {
console.error("Error Axios: ", err);
});