简体   繁体   English

使用Javascript Fetch API读取文件而无需知道文件名

[英]Read file with Javascript Fetch API without knowing the name of the file

I have a directory of text files called ./text-files . 我有一个名为./text-files的文本文件目录。 I can read files using the fetch API like this: 我可以使用fetch API读取文件,如下所示:

fetch('./text-files/foo.txt')
  then(res => {
    return res.text()
  })
  .then(text => {
    console.log(text)
  })

Does the fetch API support some way to read a directory of files without knowing the specific name of the files only the file extension? fetch API是否支持某种方式来读取文件目录,而只知道文件扩展名而不知道文件的特定名称?

Ideally, I'd like some way to get a list of all files in the directory ./text-files and then read each one serially using fetch. 理想情况下,我想要某种方法来获取目录./text-files中所有文件的列表,然后使用访./text-files读取每个文件。 Is this possible? 这可能吗? If it's possible to read one file off disk in Javascript, I would think there'd be some way to get a list of file and read each of them? 如果可以用Java脚本从磁盘上读取一个文件,我认为有某种方法可以获取文件列表并读取每个文件?

I was trying to do something like this, which didn't work: 我正在尝试做这样的事情,但是没有用:

fetch('./text-files/*.txt')
  then(res => {
    return res.text()
  })
  .then(text => {
    console.log(text)
  })

This is not possible assuming that you are attempting to read all files from a remote server directory while only using fetch. 假设仅在使用访存时尝试从远程服务器目录中读取所有文件,则这是不可能的。 You can make an API endpoint on remote machine that will return an array of files. 您可以在远程计算机上创建一个API端点,该端点将返回文件数组。 That remote API endpoint can use Node's fs module and something along the lines of: 该远程API端点可以使用Node的fs模块以及类似的东西:

fs.readdir(path, function(err, items) {
console.log(items);

for (var i=0; i<items.length; i++) {
    console.log(items[i]);
}});

Then once you fetched an array of files you can then set up them to be individually be fetched using fetch api. 然后,一旦您提取了一个文件数组,就可以将它们设置为使用fetch API分别进行提取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM