Book Image

PhantomJS Cookbook

By : Rob Friesel
Book Image

PhantomJS Cookbook

By: Rob Friesel

Overview of this book

Table of Contents (15 chapters)
PhantomJS Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading a file from PhantomJS


In this recipe, we will expand on the fs module and demonstrate how to read from a file in PhantomJS. We will cover the open method and discuss the stream object that it returns.

Getting ready

To run this recipe, we will need a script that expects to read a file from the filesystem and a target file from which to read.

The script in this recipe is available in the downloadable code repository as recipe09.js under chapter02. If we run the provided example script, we must change to the root directory for the book's sample code.

How to do it…

Consider the following script:

phantom.onError = function(message, trace) {
  console.error('[Something went wrong!] - ' + message);
  phantom.exit(1);
};

var fs    = require('fs'),
    _name = 'reamde.txt',
    path  = require('system').args[0].split(fs.separator),
    file;

path = path.slice(0, path.length - 1).join(fs.separator);

fs.changeWorkingDirectory(path);

file = fs.open(_name, 'r');

console.log('[Reading ' + _name...