简体   繁体   English

使用 Node.js 从文件夹中读取所有文件

[英]Read all files from a folder with Node.js

For reading a file from a folder it's quite straightforward.从文件夹中读取文件非常简单。 The file was in.md format and transformed to html format before sending it with POST:该文件是 in.md 格式,并在使用 POST 发送之前转换为 html 格式:

const express = require('express');
const bodyParser = require('body-parser');
const showdown = require('showdown');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

converter = new showdown.Converter();

app.post('/api/world', (req, res) => {
  fs = require('fs');
  fs.readFile(
    __dirname + '/posts/my-file.md',
    'utf8',
    function (err, data) {
      if (err) {
        return console.log(err);
      }
      text = data;
      html = converter.makeHtml(text);
      res.send(html);
    }
  );
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Now, what happens when there are more files in that folder?现在,当该文件夹中有更多文件时会发生什么? For getting those files titles I did it like:为了获得这些文件标题,我这样做了:

fs = require('fs');
fs.readdir(__dirname + '/posts', (err, files) => {
  if (err) console.log(err);
  else {
    console.log('\nCurrent directory filenames:');
    files.forEach((file) => {
      console.log(file);
    });
  }
});

The above code logs the titles of the files in that folder.上面的代码记录了该文件夹中文件的标题。

The problem appears when I want to read those files and send them as I did with the first single file at the beginning.当我想读取这些文件并发送它们时,问题就出现了,就像我在开始时对第一个单个文件所做的那样。 This is how I've tried:这就是我尝试过的方式:

app.post('/api/world', (req, res) => {
  fs = require('fs');
  fs.readdir(__dirname + '/posts', (err, files) => {
    if (err) console.log(err);
    else {
      console.log('\nCurrent directory filenames:');
      files.forEach((file) => {
        // console.log(file);
        fs.readFile(__dirname + '/posts/' + file, 'utf8', function (err, data) {
          console.log(file);
          if (err) {
            return console.log(err);
          }
          text = data;
          html = converter.makeHtml(text);
          res.send(html);
        });
      });
    }
  });
});

It throws this error:它抛出这个错误:

        res.send(html);
        ^

ReferenceError: res is not defined

I don't get it, res was defined at the top of the POST request.我不明白, res是在 POST 请求的顶部定义的。 What's wrong with it and how can it be changed to work?它有什么问题,如何改变它才能工作?

You only get ONE res.send() per request so if you're using res.send() you will have to accumulate the content and then send all the content at once.每个请求你只能得到一个res.send() ,所以如果你使用res.send() ,你将不得不积累内容,然后一次发送所有内容。

And, since you have multiple asynchronous operations all in flight at once, you will also have to keep track of when they are all done.而且,由于您同时进行了多个异步操作,因此您还必须跟踪它们何时全部完成。 This would be easiest using promises with async/await .使用带有async/await的 promises 是最简单的。

Assuming you want to just concatenate all the HTML you produce, you can do something like this:假设您只想连接您生成的所有 HTML,您可以这样做:

const fsp = require('fs').promises;
const path = require('path');

app.post('/api/world', async (req, res) => {
    try {
        let html = "";
        const basePath = path.join(__dirname, 'posts');
        const files = await fsp.readdir(basePath);
        for (let f of files) {
            const fileData = await fsp.readFile(path.join(basePath, f));
            html += converter.makeHtml(fileData);
        }
        res.send(html);
    } catch(e) {
        // log error and send error response
        console.log(e);
        res.sendStatus(500);
    }
});

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

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