javascript - 如何在 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)
解决方案
我注意到您将File对象保存在xmlFile变量中,并将其直接传递给parseFromString方法。
您不能直接从File对象解析文档对象。您应该首先使用FileReader从File对象中读取字符串。您可以使用下面的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");
推荐阅读
- thymeleaf - 为什么 Thymeleaf th:insert 删除内容直到第一个标签
- java - 自定义环境中的 QLearning 网络每次都选择相同的动作,尽管有大量的负奖励
- r - 由于引号引起的摘要错误消息
- r - 如何在ggplot2中添加人脸标签
- node.js - 使用 fs.existsSync ...我无法将输出设为 true ...(已编辑)
- flutter - 我想在应用栏之前放一张图片
- javascript - 在没有表格的情况下以ajax发送图像
- amazon-web-services - AWS 中禁用的激活服务
- python - 如何使用python在csv中用NaN替换空格、空、N/A、na和NA?
- firebase - Nuxt 服务器端渲染应用程序具有云功能的良好 SEO