首页 > 解决方案 > 如何在 Native File System API 中读取文件内容

问题描述

我正在尝试读取 XML 文件的内容。可能这是基本的 JS 东西,但我似乎无法让它工作。

我正在使用 Chrome 的实验性 Native File System API 来读取文件夹中的文件夹:

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

然后,稍后在代码中,我从主目录输入其中一个文件夹并尝试读取其中的文件。文件系统结构如下:

Directory > subdirectory > file

代码的第二部分如下所示:

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){
...

我相信问题var xmlFile = await subdirHandle.getFile('subject.xml');出在文件读取上。如果我直接从 Input 加载文件并使用FileReader(),我能够获取内容并解析它,但是使用“目录”方法我得到 null(对于评估的文档),就像这样Uncaught (in promise) TypeError: Cannot read property 'childNodes' of null

在这里编辑是我在控制台中获得的 xmlFile 变量。我只需要从中获取内容(文本格式的 XML)

xmlFile 变量的控制台日志

标签: javascriptfilegoogle-chromedomnative-file-system-api-js

解决方案


我注意到您将File对象保存在xmlFile变量中,并将其直接传递给parseFromString方法。

您不能直接从File对象解析文档对象。您应该首先使用FileReaderFile对象中读取字符串您可以使用下面的readFileAsync函数从带有 await 关键字的File对象中读取字符串:

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

推荐阅读