Wireframing | Cell 10 | Cell 12 | Search

The code initializes a process to convert a webpage to an image using the wkhtmltoimage command, with options such as quality and format, and logs the command-line arguments used. The process's output is then piped through a base64 encoder and logged, with the encoded output being passed to the $TS.jpg() function when complete.

Cell 11

$.async();
const url = 'act.com';
const options = {zoom: .5, width: 680, 'crop-h': 400, 'javascript-delay': 1000};
const encode = require('base64-stream').encode();
const spawn = require('child_process').spawn;
const myOptions = []
    .concat.apply(['-q', '-f', 'jpeg'], Object.keys(options || {}).map(k => ['--' + k, options[k]]));
const wk = spawn('xvfb-run', ['-a', '-s', '-screen 0 640x480x16', 'wkhtmltoimage', ...myOptions, url, '-']);
console.log(['-a', '-s', '-screen 0 640x480x16', 'wkhtmltoimage', ...myOptions, url, '-'].join(' '));
var out = '';
wk.stderr.on('data', (d) => console.log(d));
wk.stdout.pipe(encode).on('data', d => out += d.toString()).on('finish', () => $TS.jpg(out));

What the code could have been:

import { spawn, fork } from 'child_process';
import * as base64 from 'base64-js';
import { promisify } from 'util';

// Define constants
const URL = 'act.com';
const DEFAULT_OPTIONS = {
  zoom: 0.5,
  width: 680,
  'crop-h': 400,
  'javascript-delay': 1000,
};

// Define the options type
interface Options extends Partial {}

// Define the function to generate the image
async function generateImage(options?: Options): Promise {
  // Merge default options with provided options
  const mergedOptions = {...DEFAULT_OPTIONS,...options };

  // Create the command
  const command = [
    'xvfb-run',
    '-a',
    '-s',
    '-screen 0 640x480x16',
    'wkhtmltoimage',
    '-q',
    '-f',
    'jpeg',
   ...Object.keys(mergedOptions).map((key) => [`--${key}`, mergedOptions[key]]),
    URL,
    '-',
  ];

  // Log the command for debugging purposes
  console.log(command.join(' '));

  // Create a child process
  const wk = spawn(command[0], command.slice(1));

  // Handle errors
  wk.stderr.on('data', (d) => console.error(d));

  // Pipe the stdout to a base64 encoded string
  const encode = base64.fromByteArray;
  let out = '';
  for await (const chunk of promisify(wk.stdout).pipe(encode)) {
    out += chunk;
  }

  // Return the base64 encoded string
  return out;
}

// Generate the image and log it
$TS.jpg(await generateImage());

Code Breakdown

Initialization

Option Preparation

Process Spawning

Logging and Processing