Using node to write a simple file reading function, how to read subdirectory files

  node.js, question
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 plus'/'plus filename, (err, stat) => {
 stats[i] = stat;
 if (stat.isDirectory()) {
 Log ('plus I plus' \033[36m' plus filename plus' /\033[39m');
 } else {
 Log ('plus I plus' \033[90m' plus filename plus' \033[39m');
 bracket
 
 If (plus i = = = files.length)
 read();
 } else {
 file(i);
 bracket
 });
 };
 
 // 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)];
 Log ('plus filename');
 if (!  filename) {
 stdout.write('   \033[31mEnter your choice: \033[39m');
 } else {
 stdin.pause();
 if (stats[Number(data)].isDirectory()) {
 //I want to call back the readFile function here, so as to perform the same operation on the files under the subdirectory.
 //How should I write it?
 // readFile(dir plus'/'plus filename);
 } else {
 Fs.readFile(dir plus'/'plus filename, 'utf8', (err, data) => {
 console.log('');
 Log ('\ 033 [90m' plus data.replace ((.*)/g,' $1') plus' \033[39m');
 });
 bracket
 bracket
 };
 
 file(0);
 });
 };
 
 readFile(process.cwd());

If the readFile function is called back directly, it will result in the selection of two files with the same number in the parent directory and subdirectory, and eventually the stat.isDirectory () execution will fail.

图片描述

图片描述

Change here:

let read = () => {
 console.log('');
 stdout.write('   \033[33mEnter your choice: \033[39m');
 stdin.resume();
 stdin.setEncoding('utf8');
 stdin.once('data', option);  //Change to once
 };