JS to the end: node Learning NOTE 2

Source: Internet
Author: User

FS--CLI programming experience of node important API

The so-called "FS" is the file system!
Almost any programming language now provides APIs to read and write to the file system, such as the Open () function of the C language.

The most widespread use of the file system read-write API is CLI programming .
What is a CLI? That is, client-side programming , the early computer has no graphical interface, such as the Unix era, the general client refers to the terminal (command line terminal). Commonly known as "command-line Programs". Computer Department students C language first class and even the first semester is to do command line programming, all programming can only see the black-white characters in front of the computer screen input and output. GUI programming corresponds to CLI programming (graphical interface programming)

Go to the "FS API" io input and output

As in C, the input is called stdin, the output is called stdout, both are IO operations, collectively referred to as:stdio. Stdio is part of the node global object process!

What are the environments that use stdio? When the user needs to enter the terminal and view the output.

About the use of stdio in node:

StdOut

process.stdout.write(‘\033[33mEnter your choice: \033[39m‘);//输出一行

Stdout.write and Console.log are different, Console.log encapsulates the former and adds a newline character "\ n".

Stdin:

    process.stdin.resume();   //重置输入,建议每一次重新输入前加上,清空之前输入数据    process.stdin.setEncoding(‘utf8‘);   //编码设置,UNIX类操作系统设置为UTF-8    process.stdin.on("data",function(d){        console.log(d);    });

Note: node's process object has three streams: Stdout,stderr These two are writable streams, stdin are readable streams

FS Module--File read/write

Introduce the file module and get the exposed API:

var=require("fs");   //fs获取暴露的API

Synchronous read

console.log(fs.readdirSync(‘.‘));   //读取当前目录内容

It was previously said that in node. js it would be best to match asynchronous IO instead of this synchronous IO, since the reading of the directory process would block the subsequent code, and we would look at the directory asynchronously.

Asynchronous read

//定义一个事件回调函数functionasync (err,files){    console.log(files)}fs.readdir(".",async);

The effect is the same, but asynchronously loaded, so a callback function is required.
You see, readdir default is asynchronous read, this is the feature of node, if you need to force the use of synchronous read Readdirsync!

Write

A simple introduction to creating a file and writing a string method

var=require("fs");//在当前运行目录下创建文件并写入字符串fs.writeFile(‘./message.txt‘,‘hello node.js‘,(err)=>{    ifthrow err;    console.log("file saved");});
FS CLI Programming Combat-Directory browsing
    1. Browse files and directories in the specified directory
    2. Users can choose to open files or directories to view
    3. If the file prints the contents of the file, the directory will enter the directory to view the files in the directory.

Code:

varFs= require("FS");     //Get FS APIvarFiles= NULL;   //store read files and directories in directoryvarStats=[];     //Store file status (attributes)varDir= Process.argv[2];      //Get Parameters for CLI inputFS.Readdir(dir,function(Err,F{    Console.Log(" ");Files=F;    if(!Files.length || !Filesreturn Console.Log('\033[31m No files to show\033[39m\ n');    Console.Log("Select a file or dir");    file(0);});///recursive processing of file functionsfunction file(i){    varFileName=Files[i];    FS.Stat(dir+'/'+FileName,function(Err,Stat{Stats[i]=Stat;        if(Stat.isdirectory())Console.Log(' ['+I+']\033[36m]+FileName+'/\033[39m]);        Else            Console.Log(' ['+I+']\033[90m]+FileName+'\033[39m]);I++;        //Execute to the last file        if(I==Files.length){            Read(filename);        }Else{            file(i);        }    });}//Read file functionfunction Read(filename){    Console.Log("');    Process.stdout.Write('\033[33mEnter Your choice:\033[39m]);    Process.stdin.Resume();    Process.stdin.setencoding(' UTF8 ');    Process.stdin. on("Data",function(d){        varFile=files[ Number(d)];        varStat=stats[ Number(d)];        if(!FileProcess.stdout.Write('\033[33mEnter Your choice:\033[39m]);        Else{            Process.stdin.Pause();            if(Stat.isdirectory()){                Console.Log(dir+'/'+File+'/');                FS.Readdir(dir+'/'+File+'/',function(E,F{                    Console.Log("');                    Console.Log(' files: '+F.length);                    F.ForEach(function(FN){                        Console.Log("---"+fn;                    });                })}Else{                FS.ReadFile(dir+'/'+File,"UTF8",function(Err,Data{                    Console.Log(" "+Dir;                    Console.Log("\033[90m]+Data+"\033[39m]);                });            }        }    });}

effect :

Code Analysis:

The whole small program code is very simple, compared to the C language implementation must be much simpler. A few things to note:

    1. PROCESS.ARGV is a set of arrays that gets the parameters entered after the command line executes, such as the directory address above. But the array parameter starts with the third one, the first two are:

    1. The file function recursively handles the files and directories obtained by Readdir, which can be traversed using Files.foreach (), with the same effect.

    2. The "\033[33m", which appears in the code, is used to format the font color and can be ignored temporarily.

JS to the end: node Learning NOTE 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.