Node.js 如何等待异步调用(readdir 和 stat)

she*_*rue 2 javascript asynchronous node.js express

我正在服务器端使用 post 方法来检索请求目录中的所有文件(非递归),下面是我的代码。

我有困难发送回响应(res.json(pathContent);)与更新pathContent不使用setTimeout

我知道这是由于所使用的文件系统方法(readdirstat)的异步行为,需要使用某种回调、异步或承诺技术。

我尝试将async.waterfall的整个主体readdir用作一个函数,将 用作另一个函数res.json(pathContent),但它没有将更新后的数组发送到客户端。

我知道关于这个异步操作有成千上万的问题,但在阅读了大量帖子后无法弄清楚如何解决我的问题。

任何意见将不胜感激。谢谢。

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

var pathName = '';
const pathContent = [];

app.post('/api/files', (req, res) => {
    const newPath = req.body.path;
    fs.readdir(newPath, (err, files) => {
        if (err) {
            res.status(422).json({ message: `${err}` });
            return;
        }
        // set the pathName and empty pathContent
        pathName = newPath;
        pathContent.length = 0;

        // iterate each file
        const absPath = path.resolve(pathName);
        files.forEach(file => {
            // get file info and store in pathContent
            fs.stat(absPath + '/' + file, (err, stats) => {
                if (err) {
                    console.log(`${err}`);
                    return;
                }
                if (stats.isFile()) {
                    pathContent.push({
                        path: pathName,
                        name: file.substring(0, file.lastIndexOf('.')),
                        type: file.substring(file.lastIndexOf('.') + 1).concat(' File'),
                    })
                } else if (stats.isDirectory()) {
                    pathContent.push({
                        path: pathName,
                        name: file,
                        type: 'Directory',
                    });
                }
            });
        });
    });    
    setTimeout(() => { res.json(pathContent); }, 100);
});
Run Code Online (Sandbox Code Playgroud)

t.n*_*ese 10

最简单和最干净的方法是使用await/ async,这样你就可以使用 promise 并且代码几乎看起来像同步代码。

为此,您需要的promisified版本,readdir并且stat可以是由创建promisify的的utils核心库。

const { promisify } = require('util')

const readdir = promisify(require('fs').readdir)
const stat = promisify(require('fs').stat)

async function getPathContent(newPath) {
  // move pathContent otherwise can have conflicts with concurrent requests
  const pathContent = [];

  let files = await readdir(newPath)

  let pathName = newPath;
  // pathContent.length = 0;  // not needed anymore because pathContent is new for each request

  const absPath = path.resolve(pathName);

  // iterate each file

  // replace forEach with (for ... of) because this makes it easier 
  // to work with "async" 
  // otherwise you would need to use files.map and Promise.all
  for (let file of files) {
    // get file info and store in pathContent
    try {
      let stats = await stat(absPath + '/' + file)
      if (stats.isFile()) {
        pathContent.push({
          path: pathName,
          name: file.substring(0, file.lastIndexOf('.')),
          type: file.substring(file.lastIndexOf('.') + 1).concat(' File'),
        })
      } else if (stats.isDirectory()) {
        pathContent.push({
          path: pathName,
          name: file,
          type: 'Directory',
        });
      }
    } catch (err) {
      console.log(`${err}`);
    }
  }

  return pathContent;
}

app.post('/api/files', (req, res, next) => {
  const newPath = req.body.path;
  getPathContent(newPath).then((pathContent) => {
    res.json(pathContent);
  }, (err) => {
    res.status(422).json({
      message: `${err}`
    });
  })
})
Run Code Online (Sandbox Code Playgroud)

并且您不应该使用+ ( absPath + '/' + file)、使用path.join(absPath, file)path.resolve(absPath, file)代替连接路径。

并且您永远不应该以这样一种方式编写代码:为请求执行的代码中继到全局变量,如var pathName = '';const pathContent = [];。这可能适用于您的测试环境,但肯定会导致生产中出现问题。凡在该变量2个请求工作“同时”