koubin
koubin

Reputation: 607

How to read a file content in Native File System API

I am trying to read the content of the XML file. Probably this is basic JS stuff, but I seem can't make it work.

I am using Chrome's experimental Native File System API to read folders in folder:

const opts = {type: 'open-directory'};
handle = await window.chooseFileSystemEntries(opts);
const entries = await handle.getEntries();
...

Then, later on in the code I am entering one of the folders from the main directory and trying to read the file in it. The file system strucure is like this:

Directory > subdirectory > file

and the second part of the code looks like this:

var subdirHandle = await handle.getDirectory(oneOfTheFolders);
var xmlFile = await subdirHandle.getFile('subject.xml');
xmlDoc = domParser.parseFromString(xmlFile, "text/xml");    
parsedNumber = document.evaluate(myXpathFce('nodeInXML'), xmlDoc, null, XPathResult.ANY_TYPE, null).iterateNext();
if(parsedNumber.childNodes.length >0){
...

I believe the issue is here var xmlFile = await subdirHandle.getFile('subject.xml'); with the file reading. If I loaded the file straight from the Input and used FileReader(), I was able to get the content and parse it, but with the 'directory' approach I am getting null (for the evaluated document) like this Uncaught (in promise) TypeError: Cannot read property 'childNodes' of null

Edit here is what I get in console for the xmlFile variable. I just need to get the content (XML in text format) from this

console log for xmlFile variable

Upvotes: 1

Views: 1778

Answers (2)

DenverCoder9
DenverCoder9

Reputation: 2514

For obtaining the contents of a FileSystemFileHandle, call getFile(), which returns a File object, which contains a blob. To get the data from the blob, call one of its methods (slice(), stream(), text(), arrayBuffer()).

Upvotes: 2

Wezelkrozum
Wezelkrozum

Reputation: 996

I noticed you're saving the File object in the xmlFile variable and passing it directly into the parseFromString method.

You cannot parse a document object from a File object directly. You should first read the string from the File object using a FileReader. You can read the string from a File object with the await keyword using the readFileAsync function below:

function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsText(file);
  })
}

var file = await handle.getFile();
var text = await readFileAsync(file);
var xmlDoc = domParser.parseFromString(text, "text/xml");

Upvotes: 2

Related Questions