node.js学习第一篇

博客从一个基本的读取本地文件案例,大概介绍了Node.js的写法。代码转载自https://www.cnblogs.com/passerma/p/11067425.html 。

这篇从一个基本的读取本地文件案例,大概介绍了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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值