Search code examples
javascriptphotoshop-script

Turn CSV file into array using Vanilla Javascript without input element


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.


Solution

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