John Steam John Steam - 2 months ago 62
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'
file.changePath(path);
var write = file.write(data); //returns false
file.close();


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

Answer

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';
file.open('w');
file.write('data here');
file.close();

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

Comments