使用 node 写一个简单的文件读取函数,如何实现子目录文件的读取

var fs = require('fs'),
    stdin = process.stdin, 
    stdout = process.stdout;

var readFile = (dir) => {
  let stats = [];
  fs.readdir(dir, (err, files) => {
    // called for each file walked in the directory
    let file = (i) => {
      let filename = files[i];

      fs.stat(dir + '/' + filename, (err, stat) => {
        stats[i] = stat;
        if (stat.isDirectory()) {
          console.log('       ' + i + '   \033[36m' + filename + '/\033[39m');
        } else {
          console.log('       ' + i + '   \033[90m' + filename + '\033[39m');
        }

        if (++i === files.length) {
          read();
        } else {
          file(i);
        }
      });
    };

    // read user input when files are shown
    let read = () => {
      console.log('');
      stdout.write('   \033[33mEnter your choice: \033[39m');
      stdin.resume();
      stdin.setEncoding('utf8');
      stdin.on('data', option);
    };

    let option = (data) => {
      let filename = files[Number(data)];
      console.log('      ' + filename);
      if (!filename) {
        stdout.write('   \033[31mEnter your choice: \033[39m');
      } else {
        stdin.pause();
        if (stats[Number(data)].isDirectory()) {
          // 我想在这里回调 readFile 函数,从而对子目录下的文件执行同上的操作
          // 请问该怎么写呢?
          // readFile(dir + '/' + filename);
        } else {
          fs.readFile(dir + '/' + filename, 'utf8', (err, data) => {
            console.log('');
            console.log('\033[90m' + data.replace(/(.*)/g, '   $1') + '\033[39m');
          });
        }
      }
    };

    file(0);
  });
};

readFile(process.cwd());

如果直接回调 readFile 函数,会导致选中父目录与子目录中同编号的两个文件,最终使stat.isDirectory()执行失败

图片描述

图片描述

阅读 2.4k
1 个回答

改这儿:

let read = () => {
    console.log('');
    stdout.write('   \033[33mEnter your choice: \033[39m');
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.once('data', option);//改成once
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题