move website capture to a spawned process

This commit is contained in:
keyan 2021-10-22 17:21:38 -05:00
parent 68ddd0f86b
commit 55af57a5b7
2 changed files with 34 additions and 13 deletions

View File

@ -1,16 +1,25 @@
import Pageres from 'pageres'
import path from 'path'
const { spawn } = require('child_process');
export default async function handler (req, res) {
const url = process.env.SELF_URL + '/' + path.join(...(req.query.path || []))
res.setHeader('Content-Type', 'image/png')
try {
const streams = await new Pageres({ crop: true })
.src(url, ['600x314'])
.run()
res.status(200).end(streams[0])
} catch(e) {
console.log(e)
res.status(500)
}
return new Promise(resolve => {
const url = process.env.SELF_URL + '/' + path.join(...(req.query.path || []))
res.setHeader('Content-Type', 'image/png')
const capture = spawn(
'node', ['./spawn/capture.js', url], {maxBuffer: 1024*1024*5})
capture.on('close', code => {
if (code !== 0) {
res.status(500).end()
} else {
res.status(200).end()
}
capture.removeAllListeners()
resolve()
})
capture.on('error', err => console.log('error', err))
capture.stderr.on('data', data => console.log('error stderr', data.toString()))
capture.stdout.on('data', data => res.write(data))
})
}

12
spawn/capture.js Executable file
View File

@ -0,0 +1,12 @@
#!/usr/bin/node
const Pageres = require('pageres')
async function captureUrl () {
const streams = await new Pageres({ crop: true })
.src(process.argv[2], ['600x314'])
.run()
process.stdout.write(streams[0], () => process.exit(0))
}
captureUrl()