Writing files

There are several modes in opening a file, and so far, we have only used the read(r) mode. To open a file for writing, we can use the following syntax:

var ins = fs.open(filePath, 'w');

This will create a new stream object that we can use to write new content to. For example, in our script we have a configuration that is in JSON object format. Let us assume that the configuration object can be changed during runtime and we need that state to be saved back to configuration. Let's say we need to save some new values to our configuration file.

var config = { debug: true, home: '/home/phantomjs', username: 'tarab' }; var out = fs.open(filePath, 'w'); // File opened for writing out.write(JSON.stringify(config, null, 4)); out.close(); phantom.exit(0); ...

Get Getting Started with PhantomJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.