获取 Nightmare.JS (v 2.9.1) 屏幕截图缓冲区

Getting the Nightmare.JS (v 2.9.1) screenshot buffer

我正在尝试使用以下代码截取网页的屏幕截图。通过一些细微的修改,我可以将屏幕截图保存为 PNG。但是,nightmare.JS 文档表明如果未提供 "path" 选项,.screenshot() 方法将 return "a Buffer of the image data."。

屏幕截图执行完毕后,如何访问缓冲区?

const getScreenshot = (url) => {
    nightmare
    .goto(url)
    .wait()
    .evaluate(() => {
        const body = document.querySelector('body');

        return {
            height: body.scrollHeight,
            width: body.scrollWidth
        };
    })
    .then(function(dimensions) {
        return nightmare
        .viewport(dimensions.width, dimensions.height)
        .wait(1000)
        // .screenshot(require('path').join(__dirname, 'screenshot.png'))
        .screenshot()
    })
    .then(function(e) {
        console.log('nightmare', nightmare)
        nightmare.end()
            .then(function(result) {
            console.log('completed screenshot', result)
            console.log('done');
        })
    });
}

几乎 在那里:在您的最终 .then() 中,e 应该是 PNG 的完整缓冲区。为了验证,您可以稍微更改 .then() 函数:

    function(e) {
      //this should print "e is a buffer: true"
      console.log(`e is a buffer: ${Buffer.isBuffer(e)}`);

      return nightmare.end()
        .then(function(result) {
          console.log('completed screenshot', result)
          console.log('done');
        });
   }