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);

After opening the file for writing, we use the write function and pass the string value of the JSON object to be written to the file. With this simple function call we have written a simple content to a file.

Just as we saw while reading file contents, we can also write data to files line-per-line using the writeLine() function. This approach can be very useful while writing processed data one line at a time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.178.243