Turn CSV file into array using Vanilla Javascript without input element - javascript

I am trying to read turn a CSV file, the file is on local, could be same folder with the script file. Since I am writing JSX for photoshop, I couldn't use any other library. And there are a lot of tutorial out there using input element which is not what I need. The path of the file could be hard coded. What I am trying to do is read the CSV, and take out some data. Please advise!
Let me explain it clearly!
I am writing JSX for photoshop script which has no browser element - input tag something like that. And it must be pure Javascript no library such as jQuery. I did a lot of google search what they do is taking the input tag from browser let user select the CSV file, I just want the file path is hard code, it is a fixed path and filename. And I don't see any tutorial for read CSV file and turn into array via vanilla javascript.

You can use the File class. How this works is explained in the ExtendScript toolkit docs which are installed on your computer alongside Creative Cloud. An online version can also be found here. (The scripting guide references this under the File object on page 110, referring to a section about JavaScript on different platforms on page 32, which then refers to the ExtendScript docs.)
Example:
const file = new File("/c/Users/user/Desktop/text.csv");
file.encoding = 'UTF-8';
file.open("r");
const contents = file.read();
file.close();
alert(contents);

Related

Is there no simple way to read a local JSON or a TEXT file using plain Javascript?

I have a local JSON file. I want to create an object of that file using JS.
I tried finding some solutions and they are simply too complicated
An answer suggests that "Being able to read a local file from your browser would be a major breach of security..." so does that mean that there is NO simple way to read a local file without using FileReader or XMLHttpRequest !?
I am very disappointed as I come from a Python background and there, you can simply use a one liner "open" function to read a file.
(PS: Please do not use any AJAX or jQuery in your answers/comments)
EDIT: Somewhat more detailed description.
I have 4 files in a folder. An HTML, a CSS, A JS and one JSON file. What I want is whenever, I try to load the HTML page in a browser, my JS creates a JSON object of my local JSON file which I can display in my HTML body.

Illustrator Script: Generate a JSON file

I have been working on creating a system where I can export my swatches from Illustrator as a JSON object in order to allow for my simplicity when trying to update my App that I have created.
Using the illustrator scripting API I have managed to loop through all my swatches and generate an object. What I am attempting to do now is take this data and generate a JSON file with it. This is so that whenever I make colour updates to my App in illustrator it will immediately change everything when I run that script.
I have been making use of Adobe Documentation as well as a helpful site with it simplified and easier to navigate Jongware.
The code overall looks like this: JSFiddle
The code in question is the following. I am not sure if there is way to generate the file without making use of the API. They seem to be using the same JS engine as a browser would but I am not 100% sure. Any advice would be great!
var file = new File('filename.txt');
file.saveAs('txt');
So the main question is how would I generate a new file locally that is able to store this object I have created? As the API isnt that clear on how to create a basic text file from the data I have created.
Based off of the suggestion #enhzflep and this question.
I came to the final output of:
var file;
file = File.saveDialog('Export');
file.open('w');
file.write(JSON.stringify(colourObject));
file.close();
Making use of Douglas Crockfords JSON2 Pollyfill (As Illustrator scripts dont support .stringify) to create a stringify method I was able to create a JSON exported file.

Including a text file in Chrome extension and reading it with Javascript

I want to create a Chrome extension that contains a text file with static data (a dictionary of English words) and I want the extension to be able to parse that file. I've only managed to find FileReader class, but it looks like it's made for reading user-selected files, while in my case I always want to read the same exact file included in extension's package. As a workaround, I can convert the file to a Javascript array of strings declared in some .js file included in the manifest, but in that case the whole contents would be loaded into memory at once, while what I need is to read the data line by line. Is there any way to do this?
You can go the FileReader route, since you can obtain the Entry of your package directory with chrome.runtime.getPackageDirectoryEntry().
However, an easier way is to just make a XHR to your file using chrome.runtime.getURL() with a relative path. The first way is useful when you want to list files, though.

Generate a Word document in JavaScript with Docx.js?

I am trying to use docx.js to generate a Word document but I can't seem to get it to work.
I copied the raw code into the Google Chrome console after amending line 247 to fix a "'textAlign' undefined error"
if (inNode.style && inNode.style.textAlign){..}
Which makes the function convertContent available. The result of which is an Object e.g.
JSON.stringify( convertContent($('<p>Word!</p>)[0]) )
Results in -
"{"string":
"<w:body>
<w:p>
<w:r>
<w:t xml:space=\"preserve\">Word!</w:t>
</w:r>
</w:p>
</w:body>"
,"charSpaceCount":5
,"charCount":5,
"pCount":1}"
I copied
<w:body>
<w:p>
<w:r>
<w:t xml:space="preserve">Word!</w:t>
</w:r>
</w:p>
</w:body>
into Notepad++ and saved it as a file with an extension of 'docx' but when I open it in MS Word but it says 'cannot be opened because there is a problem with the contents'.
Am I missing some attribute or XML tags or something?
You can generate a Docx Document from a template using docxtemplater (library I have created).
It can replace tags by their values (like a template engine), and also replace images in a paid version.
Here is a demo of the templating engine: https://docxtemplater.com/demo/
This code can't work on a JSFiddle because of the ajaxCalls to local files (everything that is in the blankfolder), or you should enter all files in ByteArray format and use the jsFiddle echo API: http://doc.jsfiddle.net/use/echo.html
I know this is an older question and you already have an answer, but I struggled getting this to work for a day, so I thought I'd share my results.
Like you, I had to fix the textAlign bug by changing the line to this:
if (inNode.style && inNode.style.textAlign)
Also, it didn't handle HTML comments. So, I had to add the following line above the check for a "#text" node in the for loop:
if (inNodeChild.nodeName === '#comment') continue;
To create the docx was tricky since there is absolutely no documentation on this thing as of yet. But looking through the code, I see that it is expecting the HTML to be in a File object. For my purposes, I wanted to use the HTML I rendered, not some HTML file the user has to select to upload. So I had to trick it by making my own object with the same property that it was looking for and pass it in. To save it to the client, I use FileSaver.js, which requires a blob. I included this function that converts base64 into a blob. So my code to implement it is this:
var result = docx({ DOM: $('#myDiv')[0] });
var blob = b64toBlob(result.base64, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
saveAs(blob, "test.docx");
In the end, this would work for simple Word documents, but isn't nearly sophisticated for anything more. I couldn't get any of my styles to render and I didn't even attempt to get images working. I've since abandoned this approach and am now researching DocxgenJS or some server-side solution.
You may find this link useful,
http://evidenceprime.github.io/html-docx-js/
An online demo here:
http://evidenceprime.github.io/html-docx-js/test/sample.html
You are doing the correct thing codewise, but your file is not a valid docx file. If you look through the docx() function in docx.js, you will see that a docx file is actually a zip containing several xml files.
I am using Open Xml SDK for JavaScript.
http://ericwhite.com/blog/open-xml-sdk-for-javascript/
Basically, on web server, I have a empty docx file as new template.
when user in browser click new docx file, I will retrieve the empty docx file as template, convert it to BASE64 and return it as Ajax response.
in client scripts, you convert the BASE64 string to byte array and using openxmlsdk.js to load the byte array as an javascript OpenXmlPackage object.
once you have the package loaded, you can use regular OpenXmlPart to create a real document. (inserting image, creating table/row ).
the last step is stream it out to end user as a document. this part is security related. in my code I send it back to webserver and gets saved temporarily. and prepare a http response to notify end user to download it.
Check the URL above, there are useful samples of doing this in JavaScript.

Obtaining the absolute path of a file selected with a HTML file chooser button using JavaScript

I am developing a small Java application with a web interface using Javafx (with a WebView component).
I am wondering how can I know with JavaScript the absolute path of a file selected with a file chooser in HTML, so I can pass that path to my Java application.
Using JQuery, I tried with this:
var completeFileName = $('#button_id').val();
but this is returning the name of the file only, not its complete path.
If this is not possible I will have to add a Java file chooser in the javafx stage, but it will be a pity since all the interface components of my application are in html and I wanted to keep it like that.
in html 4 its not going to happen, even in HTML 5 i don think you can get anny detailed info about the clients file system.
random google result about this: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Categories