John Steam John Steam - 1 year ago 262
Javascript Question

How do I save a text file using an InDesign script?

I'm extracting some data from an InDesign INDD file using a script. I'd like to save my data in a txt or json file, but my file is not saving successfully.

var data = 'string of data';
var filename = 'CS111.json';

var file = new File(filename);
var path = file.saveDlg(); //returns a valid path, but with spaces as '%20'
var write = file.write(data); //returns false

What am I missing here? The file doesn't show up in the chosen folder.

Answer Source

There are at least four steps in saving a file using InDesign Javascript: get a path and filename, create a file object, open the file, write to the file, and close the file.

I find that the write step will sometimes fail if I don't set the encoding.

//Define path and file name
var path = '~/Documents/';
var filename = 'filename.txt';

//Create File object
var file = new File(path + filename);

file.encoding = 'UTF-8';'w');
file.write('data here');

Documentation: File class, .open(), .write()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download