美文网首页
17-2-了不起的Nodejs-代码-01

17-2-了不起的Nodejs-代码-01

作者: magic_pill | 来源:发表于2017-12-19 21:08 被阅读17次

    一、web-server

    var http = require("http");
    
    http.createServer(function(req,res){
        res.writeHead(200,{"Content-Type":"text/html"});
        res.end("<strong>node,我来了</strong>")
    }).listen(3001);
    
    require("colors");
    console.log("smashing node".rainbow);
    
    console.log(1);
    process.nextTick(function () {
        console.log(3);
    });
    console.log(2);
    
    console.log(4);
    setImmediate(function(){
        console.log(6);
    });
    console.log(5);
    

    二、emit

    var emitter = require("events").EventEmitter;
    
    var a = new emitter();
    
    a.on("aa",function(){
        console.log("aaa");
    });
    
    a.emit("aa");
    a.emit("aa");
    a.emit("aa");
    
    //只执行一次的事件
    a.once("ha",function(){
        console.log("bbb");
    });
    a.emit("ha");
    a.emit("ha");
    a.emit("ha");
    
    var buf = new Buffer("a1231da","base64");
    console.log(buf);
    

    三、file-exporer

    /**
     * Created by yjw on 2017/12/18.
     */
    
    var fs = require("fs");
    var stdin = process.stdin;
    var stdout = process.stdout;
    
    fs.readdir(process.cwd(),function(err,files){
        if(!files.length){
            return console.log("   \033[31m No files to show \033[39m");
        }
        console.log(" Select witch file or directory you want to see \n");
    
        var states = [];
        function file(i){
            var filename = files[i];
            fs.stat(process.cwd() + "/" + filename,function(err,stats){
                states[i] = stats;
                //判断是否是文件夹
                if(stats.isDirectory()){
                    console.log("  " + i + "  directory:\033[31m" + filename + "/\033[39m");
                }else{
                    console.log("  " + i + "  file:\033[36m " + filename + "\033[39m");
                }
    
                i++;
                if(i == files.length){
                    read();
                }else{
                    file(i);
                }
            });
    
            function read(){
                stdout.write("  \033[31m Enter your choice: \033[39m");
                stdin.resume();
                stdin.setEncoding("utf-8");
    
                stdin.on("data",option)
            }
    
            function option(data){
                //通过下标获取文件
                var file = files[Number(data)];
                if(!file){
                    stdout.write("  \033[31m Enter your choice: \033[39m")
                }else{
                    stdin.pause();
    
                    if(states[Number(data)].isDirectory()){
                        fs.readdir(__dirname + "/" + file,function(err,files){
                            console.log(" There are \033[31m" + files.length + "\033[39m files!" );
                            files.forEach(function(file){
                                console.log("   -    " + file);
                                //stdin.resume();
                                //stdin.setEncoding("utf-8");
                                //stdin.on("data",function(data){
                                //    var file = files[Number(data)];
                                //    fs.readFile(__dirname + "/" + file,function(err,data){
                                //        console.log("  in  " + data);
                                //    })
                                //})
                            });
                        })
                    }else{
                        fs.readFile(__dirname + "/" + file,"utf-8",function(err,data){
                            console.log("\033[31m " + data.replace(/(.*)/g,"  $1") + "  \033[39m");
                        })
                    }
                }
            }
        }
    
        file(0);
    });
    
    console.log(process.argv);
    //fs.readdir(process.cwd(),function(err,files){
    //    console.log(" ");
    //    //如果没有文件,则打印
    //    if(!files.length){
    //        return console.log("    \033[31m No files to show!\033[39m  \n");
    //    }
    //    console.log(" Select witch file or directory you want to see\n");
    //
    //    function file(i){
    //        var filename = files[i];
    //
    //        fs.stat(__dirname + "/" + filename,function(err,stats){
    //
    //            if(stats.isDirectory()){
    //                console.log(" directory:  " + i + "   \033[36m" + filename + "/\033[39m");
    //            }else{
    //                console.log("  " + i + "  \033[36m" + filename + "\033[39m");
    //            }
    //
    //            i++;
    //            if(i == files.length){
    //                console.log(" ");
    //                process.stdout.write("  \033[33mEnter your choice: \033[39m");
    //                process.stdin.resume();
    //                process.stdin.setEncoding("utf8");
    //            }else{
    //                file(i);
    //            }
    //        });
    //    }
    //    file(0);
    //});
    

    四、fs

    //同步获取当前目录下的文件列表
    console.log(require("fs").readdirSync(__dirname));
    console.log(process.cwd());
    console.log(require("fs").stat);
    
    console.log(require("fs").readdirSync(__dirname));
    
    //异步获取当前目录下的文件列表
    require("fs").readdir(".", function (err, file) {
        console.log("异步获取当前目录下的文件列表:" + file)
    });
    require("fs").readdir(".",function(err,file){
        console.log(file.length)
    });
    

    五、cli-api

    /**
     * Created by yjw on 2017/12/19.
     */
    
    //argv
    //第一个值为 node 所在的路径
    //第二个值为当前文件的路径
    console.log(process.argv.slice(2));
    
    //当前执行文件在文件系统中的位置
    console.log(__dirname);
    //获取程序运行时的当前工作目录
    console.log(process.cwd());
    
    //更改工作目录 chdir
    //process.chdir("/");
    console.log(process.cwd());
    //process.exit(1);
    
    //通过 env 来获取环境变量,举例如下:
    console.log(process.env.JAVA_HOME);
    
    //退出程序
    console.error("An error occurred!");
    //process.exit(1);
    
    //暂时报错
    //process.on("SIGKILL",function(){
    //    console.log("收到进程终止信号");
    //});
    
    // ANSI 转义码 \033表示开始,[表示开始颜色设置,m代表颜色结束,39表示将颜色再设置回去
    console.log("\033[31m 我是谁 \033[39m");
    
    var fs = require("fs");
    //fs.readFile("",function(err,content){
    //    console.log("  --1---" + content);
    //    console.log("\033[31m ************************************************** \033[39m");
    //});
    
    //stream
    var stream = fs.createReadStream("aaa.txt");
    var a = "";
    stream.on("data",function(data){
        //处理文件部分内容
        a += data;
        console.log(a);
        console.log("\033[31m ************************************************** \033[39m");
    });
    stream.on("end",function(){
        console.log("文件处理结束");
    });
    
    //监视
    fs.readdir(process.cwd(),function(err,files){
        files.forEach(function(file){
            if(/\.js/.test(file)){
                fs.watchFile(process.cwd() + "/" + file,function(){
                    console.log(" ---  " + file + " 文件发生变化了!");
                })
            }
        })
    });
    

    六、http服务器

    /**
     * Created by yjw on 2017/12/19.
     */
    
    require("http").createServer(function(req,res){
        res.writeHead(200,{"Content-Type":"text/html"});
        res.end("<h2>Hello World</h2>")
    }).listen(3000);
    
    //node 服务器端,通过 \n 来判断消息是否已完全到达。
    

    七、net服务器

    /**
     * Created by yjw on 2017/12/19.
     */
    
    var count = 0;
    
    var server = require("net").createServer(function(conn){
        count++;
        console.log("  \033[31m  New connection!  \033[39m");
        conn.write(" > Welcome to TongHuaBang \n" +
            " There is \033[31m " + count + "\033[39m 连接 at this time.\n " +
            "> please write your name and press enter: ");
    
        //终止事件有两个,一个是end,一个是close。当关闭telnet时,会发送一个名为“FIN”的包
        //给服务器,意味着结束连接,但是连接发生错误时,end事件不会触发。但是这两种情况下,close都会触发,所有择优使用close
        conn.on("close",function(){
            count--;
            console.log("失去一个连接");
        })
    });
    
    server.listen(3001,function(){
        console.log("  \033[31m  listen on port: 3001 \033[39m");
    });
    

    八、net服务器

    /**
     * Created by yjw on 2017/12/19.
     */
    
    var count = 0,
        users = {};
    var server = require("net").createServer(function(conn){
        //建立连接
        console.log("  New Connection!  ");
        conn.write("\n Welcome to TongHuaBang " +
            "\n There are \033[31m" + count + "\033[39m other people conneting at this time " +
            "\n Please write your nickname:");
        count++;
    
        //设置编码格式为 utf8,否则输出的是 buffer 格式数据(另一种方法是:data.toString("utf8"))
        conn.setEncoding("utf8");
        var nickname;
    
        //发送广播
        function broadcast(msg,exceptMyself){
            for(var i in users){
                if(!exceptMyself || i!=nickname){
                    users[i].write(msg);
                }
            }
        }
        //接收数据
        conn.on("data",function(data){
            //删除回车符
            data = data.replace('\r\n','');
    
            if(!nickname){
                if(users[data]){
                    conn.write("\033[31m nickname already in use,try again: \033[39m");
                    return;
                }else{
                    nickname = data;
                    users[data] = conn;
    
                    for(var i in users){
                        //users[i].write("\033[31m > " + nickname + " \033[39m joined the room");
                        broadcast("\033[31m > " + nickname + " \033[39m joined the room")
                    }
                }
            }else{
                //否则,视为聊天消息
                for(var i in users){
                    //if(i != nickname){
                    //    users[i].write("\033[31m > " + nickname + " : \033[39m" + data + "\n");
                    //}
                    broadcast("\033[31m > " + nickname + " : \033[39m" + data + "\n",true)
                }
            }
        });
    
    
        //断开连接
        conn.on("close",function(){
            console.log("断开一个连接");
            count--;
            delete users[nickname];
            broadcast(nickname + ' left the room')
        });
    });
    
    server.listen("3002",function(){
        console.log(" 建立连接,端口号为 3002")
    });
    

    九、net-客户端

    //var net = require("net");
    //var client = net.connect(3002,"localhost");
    //client.on("connect",function(){
    //    console.log("我已经连接上啦");
    //});
    //
    ////如果提供了回调函数,就等于监听了该方法返回的对象上的 connect 事件
    //net.connect(3002,"localhost",function(){
    //    console.log("我连上了");
    //});
    
    var client2 = require("net").connect(6667,"irc.freenode.net");
    client2.setEncoding("utf-8");
    client2.on("connect", function () {
        console.log("--------------");
        client2.write("NICK mynick\r\n");
        client2.write("USER mynick 0 * :realname\r\n");
        client2.write("JOIN #node.js\r\n");
        //其中,\r\n是HTTP协议用来区分头信息的分隔符
    });
    

    相关文章

      网友评论

          本文标题:17-2-了不起的Nodejs-代码-01

          本文链接:https://www.haomeiwen.com/subject/gbgiwxtx.html