F
F
Franco Mannino2017-04-26 13:47:28
JavaScript
Franco Mannino, 2017-04-26 13:47:28

How to properly open a text file with a Javascript script?

The situation is this: I'm making a "screenshot" of URLs based on PhantomJS, and for now I keep the list of URLs in a text file. Script that takes screenshots (and reads urls from a file) - in JS. I start it from the console - everything works fine, but when I start it via CRON - it does not read the file.
How it is better to implement it? Or a different architecture altogether? Code below:

var fs = require('fs');
var content = fs.read('urls.txt');
var address = content.split('\r\n');

var addlen = address.length;
var counter = 0;

address.forEach(function (entry) {

    // имя файлу присваиваем по юникс-времени
    var now = new Date();
    var name = now.getTime() + '.png';

    var page = require('webpage').create();
    page.settings = {
        javascriptEnabled: true,
        loadImages: true,
        resourceTimeout: 20000,
        userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/19.0'
    };

    page.viewportSize = { width: 1024, height: 800 };

    try {       

        page.open(entry, function (status) {

        counter++;

            if (status !== 'success') {
                console.log(counter + '  Unable  ' + entry);                
                if ( counter == addlen ) { phantom.exit(); };
            }

            else {
                page.render(counter + " " + name);
                console.log(counter +' Saccess ' + entry);
                if ( counter == addlen ) { phantom.exit(); };
            }
            page.close();
        });
    }

    catch (e) {
        console.log('Ошибка работы PhantomJS.');
        console.log('Сообщение ошибки:');
        console.log(e);
        phantom.exit();
    }
});

if ( counter == addlen ) { phantom.exit(); };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2017-04-26
@garinov

This is how you can implement reading a file https://jsfiddle.net/Politonius/uh2fLao0/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question