node study notes (a) local file directory Viewer

Node.js

img

news

nw.js front-end development of desktop applications

content

node.js combat as usual, provide Baidu cloud link, originally I thought that this series is real, but it is not, but this is also good

Links: https://pan.baidu.com/s/1HC2Vhv2EwnYJs0htDTpQTg
extraction code: wws9

Rookie tutorial to the event loop

Readily Notes

img

Node core technology

Node told to do something, and after the completion of the transfer node to tell who

The first application

var http = require('http');

http.createServer(function (request, response) {

    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain 还有application/json这个
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 "Hello World"
    response.end('Hello World\n');
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

Class definition

function shape() {
    this.x=0;
    this.y=0;
    this.move=function (x,y) {
        this.x=x;
        this.y=y;
    }
    this.distance=function () {
        return Math.sqrt(this.x*this.x+this.y*this.y);
    }
}
var s=new shape();
s.move(10,10);
console.log(s.distance());

Add the class using the object prototype

function shape() {}
shape.prototype.x=0;
shape.prototype.y=0;
shape.prototype.move=function (x,y) {
    this.x=x;
    this.y=y;
}
shape.prototype.distance=function () {
    return Math.sqrt(this.x*this.x+this.y*this.y);
}
var s=new shape();
s.move(10,10);
console.log(s.distance());

console

warn print standard error
time standard timestamp
after timeEnd time and how long it took
assert threw an exception

//延时
console.log('start');
setTimeout(function () {
    console.log('i have done my work');
},2000)//2000就是两秒
//异步读文件
var fs=require('fs');
fs.open(
    'gou.txt','r',
    function (err,handle) {
        if(err){
            console.log("Error"+err.code+"("+err.message+")");
            return;//注意报了错之后要返回
        }
        var buf=new Buffer(100000);
        fs.read(
            handle,buf,0,100000,null,
            function(err,length){
                if(err){
                    console.log("Error"+err.code+"("+err.message+")");
                    return ;
                }
                console.log(buf.toString('utf-8',0,length));
                fs.close(handle,function(){})
            }
        )
    }
)
//输完所有的参数后,要有一个function(err,什么参数),if(err)怎么样,之后再有一个处理
var fs=require('fs');
function FileObject() {
    this.filename="";
    this.file_exists=function (callback) {
        var me=this;//异步回调插入事件队列后,执行完返回不再有FileObject的继承关系了,要有重新的this指针,用一个变量代替this,可以使this保留下来
        console.log('try to open',me.filename);
        fs.open(this.filename,'r',function (err,handle) {
            if(err){
                console.log(err.stack);
            }
            fs.close(handle,function () {

            });
            callback(null,true);
        });

    }
};
var fo=new FileObject();
fo.filename='ou.txt';
fo.file_exists(function (err,results) {
   if(err)
   {
       console.log('oh! xiba!'+err.stack);
   }
   console.log('file exits!');
});

err

It is null, which indicates success, and there will be a return value
is an Error object instance, occasionally see inconsistencies
callback (null, a) // no error, the value of a send back

Callback

Most of the callback function in all load after this function is called, the callback function has its own callback prototype, err parameter and a result parameter

process.nextTick

I give up the initiative, you can perform the functions I give you in your free time, time to time to handle other tasks once

Build server

var http=require('http');
function f(req,res) {
    de(req.method);
    res.writeHead(200,{"Content-Type":"application/app"});
    res.end(JSON.stringify({error:null})+'\n');//选中后会下载一个文件
}
var s=http.createServer(f);//把处理函数作为参数传进去
s.listen(8080);
//一个查看本地照片目录的应用
var http=require('http');
var fs=require('fs');
function f(callback) {
    fs.readdir(
        "img",
        function (err,files) {
            if(err){
                callback(err);//第一个参数喂err,第二个参数不用你管了
                return ;
            }
            callback(null,files);//没有错误,带回文件
        }
    );
}
function g(req,res) {
    de(req.method);
    f(function (err,albums) {
        if(err){
            res.writeHead(503,{'Content-Type':'application/json'});//就相当于错误404
            res.end(JSON.stringify(err)+'\n');
        }
        var out={
            error:null,
            data:{albums:albums}
        };
        res.writeHead(200,{"Content-Type":"application/json"});
        res.end(JSON.stringify(out)+'\n');//把输出json化,别忘了带一个回车
    });
}
var s=http.createServer(g);
s.listen(8080);
//{"error":null,"data":{"albums":["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]}}

Event Loop

//readFileSync是同步的,后面不能加回调函数,去掉Sync即可回调
//应该先on好处理器,再emit信号
// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

// 创建事件处理程序
var connectHandler = function connected() {
   console.log('连接成功。');
  
   // 触发 data_received 事件 
   eventEmitter.emit('data_received');
}

// 绑定 connection 事件处理程序
eventEmitter.on('connection', connectHandler);
 
// 使用匿名函数绑定 data_received 事件
eventEmitter.on('data_received', function(){
   console.log('数据接收成功。');
});

// 触发 connection 事件 
eventEmitter.emit('connection');

console.log("程序执行完毕。");

Guess you like

Origin www.cnblogs.com/Tony100K/p/11608466.html