码迷,mamicode.com
首页 > Web开发 > 详细

node.js学习第一篇

时间:2019-06-22 01:31:25      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:cto   bsp   director   div   adf   stat   fun   err   写法   

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

 

node.js学习第一篇

标签:cto   bsp   director   div   adf   stat   fun   err   写法   

原文地址:https://www.cnblogs.com/passerma/p/11067425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!