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

Saving a file from a PhantomJS script


Now we will introduce the fs module which provides an API for working with the filesystem from a PhantomJS script. In this recipe, we will demonstrate how to save a file from PhantomJS and use the separator property for generating filesystem-safe paths, checking whether the target directory exists, creating it if it does not, checking write permissions if it does, and then persisting the contents to the filesystem.

Getting ready

To run this recipe, we will need a script that expects to write a file to the filesystem. In order to write that file, we need write permissions in the destination directory.

The script in this recipe is available in the downloadable code repository as recipe08.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:

var fs        = require('fs'),
    targetDir = 'foo-log';

if (!fs.exists(targetDir)) {
  console.log('Creating...