这篇从一个基本的读取本地文件案例,大概介绍了node.js的写法,代码如下
1 var fs = require(‘fs‘); 2 var stats = []; 3 fs.readdir(process.cwd(), function(err, files){ 4 console.log(files); 5 console.log(‘ ‘); 6 if(!files.length){ 7 return console.log(‘ \033[31m No file to show!\033[39m\n‘); 8 } 9 console.log(‘ Select which file or directory you want to see\n‘); 10 function file(i) { 11 var filename = files[i]; 12 fs.stat(__dirname + ‘/‘ +filename, function (err, stat) { 13 stats[i] = stat; 14 if(stat.isDirectory()){ 15 console.log(‘ ‘+i+‘ \033[36m‘ + filename + ‘/\033[39m‘); 16 } else { 17 console.log(‘ ‘+i+‘ \033[90m‘ + filename + ‘\033[39m‘); 18 } 19 i++; 20 if(i == files.length){ 21 console.log(‘ ‘); 22 process.stdout.write(‘ \033[33mEnter your choice: \033[39m‘); 23 process.stdin.resume(); 24 process.stdin.setEncoding(‘utf8‘); 25 process.stdin.on(‘data‘, function (data) { 26 var filename = files[Number(data)]; 27 if(!files[Number(data)]){ 28 process.stdout.write(‘ \033[33mEnter your choice: \033[39m‘); 29 } else { 30 process.stdin.pause(); 31 if(stats[Number(data)].isDirectory()){ 32 fs.readdir(__dirname + ‘/‘ +filename, function (err, files) { 33 console.log(‘ ‘); 34 console.log(‘ ( ‘+files.length + ‘files )‘); 35 files.forEach(function (file) { 36 console.log(‘ - ‘ + file); 37 }); 38 console.log(‘ ‘) 39 }) 40 } else { 41 fs.readFile(__dirname+‘/‘+filename, ‘utf8‘, function (err, data) { 42 console.log(‘ ‘); 43 console.log(‘\033[90m‘+ data.replace(/(.*)/g, ‘ $1‘)+‘\033[39m‘); 44 }) 45 } 46 } 47 }) 48 } else { 49 file(i); 50 } 51 }) 52 } 53 file(0); 54 });
原文地址:https://www.cnblogs.com/passerma/p/11067425.html
时间: 2024-11-05 18:54:47