首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

读书笔记-《了不起的node.js》-4

未知的总是让我们恐惧,打破恐惧的方法只能是走近未知!

今天下班去吃饭的路上拍的;怀念啊,我们的青春啊~

Node重要API

命令行工具CLI以及FS API

还是读书笔记,但是这个不是理论知识喽,47-57页带着我们编写了首个node程序;

具体需求:

  • 程序需要在命令行运行
  • 程序启动后,显示当前目录下的文件和目录列表
  • 选择某个文件后,显示该文件内容

speak is cheap ! 跟我一起动手敲吧,各位宝宝!

代码语言:javascript
复制

// index.js
var fs = require('fs');
var stdout = process.stdout;
var stdin = process.stdin;


//列出当前目录下的文件,等待用户输入 process.cwd() 返回运行当前脚本的工作目录的路径
fs.readdir(process.cwd(),function(err,files){
  // files为空,则告诉对象,没有文件
  if(!files.length){
    // \033[31m和\033[39m是为了让文字呈现红色
    return console.log('   \033[31m No files to show!\033[39m\n');
  }
  console.log(' select which file or directory you want to see\n');
  function file(i){
    // 获取文件名
    var filename =files[i];
    // fs.stat会给出文件或者目录的元数据 ,__dirname总是执行执行的js文件的绝对路径
    fs.stat(__dirname + '/' + filename ,function(err,stat){
      stat[i]=stat;
      // 查看路径是不是目录
      if(stat.isDirectory()){
        console.log('  '+ i +'   \033[36m'+ filename+'/\033[39m');
      }else{
        console.log('  '+ i +'   \033[90m'+ filename+'\033[39m');
      }

      i++;
      if(i==files.length){ //当所有文件都处理完了,提示用户选择
        read();
      }else{
        file(i); //如果文件未处理完,则用递归处理
      }

    })
  }
  file(0);
  function read(){
    console.log('');
    // stdout.write相比于console.log不用换行,让用户直接在提示语后输入
    stdout.write('   \033[33mEnter you choice: \033[39m');
    //等待用户输入
    stdin.resume();
    //紧跟着这行代码设置流编码为utf8
    stdin.setEncoding('utf8');
    stdin.on('data',option);
  }
  function option(data){
    //讲utf8编码的字符串转换成number类型来方便检查
    var filename = files[Number(data)]; 
    // 检验用户的输入是否匹配数组的下标,如不匹配文字,输出‘Enter you choice:’
    if(!filename){
      stdout.write( '   \033[36mEnter you choice: \033[39m');
    }else{
      //如果通过将流停止,以便做完fs操作后退出程序
      stdin.pause();
      //读取文件,并用正则表达式做一些辅助缩进,并console log;
      fs.readFile(__dirname + '/'+ filename,'utf8',function(err,data){
        console.log(' \033[90m'+data.replace(/(.*)/g,'  $1') +'\033[39m')
      })
    }
  }
})

我的文件目录结构:

test.js文件内容:

代码语言:javascript
复制


console.log("我是test文件,看你能读到我不??");

在终端执行结果:

恭喜!你完成了首个node命令行(CLI)程序!

愿我们有能力不向生活缴械投降---Lin

下一篇
举报
领券