nodejs学习笔记2

回调

 vi readfile.txt

写点测试数据在里面

vi test.js

var fs = require("fs");

fs.readFile('readfile.txt', function(err,data){

       if(err) return console.error(err);

       condole.log(data.toString());

});


console.log("finished the program!");

然后执行

node test.js

不需要等待文件读取完,这样就可以在读取文件时同时执行接下来的代码,非阻塞

node.js是单线程,它的事件机制是用设计模式中观察者模式实现

javaScript语言只有字符串数据类型,但在处理tcp或文件流时,要用到二进制数据,所以node.js中定义了一个buffer类,感觉类似数组.

var buf1 = new Buffer('abc');

var buf2 = new Buffer('def');

var buf3 = Buffer.concat([buffer1,buffer2]);

console.log("buffer3内容:" + buffer3.toString());

Buffer还有很多方法,比如tojson,compare


创建模块

vi main.js

var hello = require('./hello');

hello.workd();

这里引用了hello,所以我们来创建个hello.js

vi hello.js

exports.world = function(){

console.log('Hello World');

}

或者

vi hello.js

function Hello(){

var name;

        this.setName = function(thyName){

name = thyName;

}

this.sayHello = function(){

console.log('hello ' + name);

}

};

module.exports = Hello;

然后可以在main.js中这样用

var Hello = require('./hello');

hello = new Hello();

hello.setName('Lawson');

hello.sayHello();


写的比较乱


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值