LoginSignup
6
7

More than 5 years have passed since last update.

nodeからphantomjs呼び出して、スクリーンショット取得したファイルが存在しなかったらrender.js呼び出して実行して、ファイルがあったら何もしない君

Posted at

OSXでsourceからbuildして動かしたヤツ

文字化けしないですんなり動いたけど
CentOS5系で日本語フォント入れたり /etc/fonts/local.conf とか
~/.fonts.conf とかつくっても文字化け治らなくてないた。

取り敢えず日本語フォントはまだイケてないけど動作自体は期待した通りに動いた。

fs.js
// gazo_fileがあるかないかの確認
var fs = require('fs');
var path = require('path');
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;
var render = "render.js";

// この辺が引数みたいな感じで渡したい
var gazo_name = "www.google.co.jp";
var gazo_file = gazo_name + ".png";
var width   = "120";
var height  = "80";

// あるかないかの確認
fs.exists(gazo_file, function (exists) {
    if (exists) {
        console.log(gazo_file , "is exists!");

    // gazo_fileがなかったらつくる
    } else {
        var url = "http://" + gazo_name;
        var options = [
            render,
            url,
            gazo_file,
            width,
            height
        ];

        // ここでrender.jsをphantomjsで呼び出して実行する
        childProcess.execFile(binPath, options, function(error, stdout, stderr) {
            console.log(stdout);
            console.error(stderr);
            if (error != null) {
                console.error('error: ' + error);
            }
        });
        console.log(gazo_file , "nothing. create this file!");
    }
});
render.js
var page = require('webpage').create();

// argsは、phantom.argsでアクセスできる。
var address = phantom.args[0];
var output  = phantom.args[1];
var width   = phantom.args[2];
var height  = phantom.args[3];

console.log(address);
console.log(output);
console.log(width);
console.log(height);

page.viewportSize = {width: width, height: height, margin:'0px'};

page.open( address, 
                      function(status){
                           console.log(status);
                           if( status !== 'success'){
                               console.log('error');
                           }
                           else{
                               // 出力
                               page.render(output);
                               // 終了
                               phantom.exit();
                           }
                       }
           );
6
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7