NightMare でスクリーンショットを撮る時にディレクトリを作成する


Nightmare を使ってテストする時にスクリーンショットを撮るのですが、指定したディレクトリが存在しなかった場合、作成してから保存したい。

そんなときは make-dir - npm を使用する。

make-dirはサブディレクトリも含めて存在しなければ作成してくれるスグレモノ。
使い方も簡単。

Nightmare/node_modules/eramthgin/lib/actions.js を修正する。

actions.js
var paths = require('path');
var makeDir = require('make-dir');

// 中略

exports.screenshot = function (path, clip, done) {
  debug('.screenshot()');
  if (typeof path === 'function') {
    done = path;
    clip = undefined;
    path = undefined;
  } else if (typeof clip === 'function') {
    done = clip;
    clip = (typeof path === 'string') ? undefined : path;
    path = (typeof path === 'string') ? path : undefined;
  }
  this.child.call('screenshot', path, clip, function (error, img) {
    var buf = new Buffer(img);

   // debug('.screenshot() captured with length %s', buf.length);
    // path ? fs.writeFile(path, buf, done) : done(null, buf);
    // ↓
    makeDir(paths.dirname(path)).then(res => {
      console.log(res);

      debug('.screenshot() captured with length %s', buf.length);
      path ? fs.writeFile(path, buf, done) : done(null, buf);
    });

  });
};