nodejs写入文件的一个小bug

使用fs的appendFile写日志,线上某些机器报

TypeError: object is not a function

查看报错行内容是 fs.appendFile(file , logTxt + "\n")  ,看手册上这个调用方法为

fs.appendFile(filename, data, encoding='utf8', [callback])

貌似调用没什么问题,而且之前代码也运行正常

 

万能google给了答案 》》https://github.com/joyent/node/issues/4352

Repeated calls to fs.appendFile without callback will cause an error

当调用fs 又没设置回调函数的时候会报错

This only happens if you choose not to pass in a callback to the method. This is because an EMFILE error occurs, since there are too many open file handles, and the code wishes to pass an error to the user, however the documentation does indicate that the callback should be optional.

看来这是个bug,要它不报错倒是简单, 传个空函数 function(){} 作为回调函数就好了

 

PS 

Error: EMFILE, too many open files 可以通过设置系统参数修改

sysctl -w kern.maxfiles=20480

 

PS2 文件句柄过段时间会自己回收掉 如果调用不是很频繁的话 就不会触发这个报错  ,线上是上了一个访问量很大的页面才暴露了这个问题

 

 PS3 任何IO操作都可能导致EMFILE这个异常

比如打开多个socket端口

var count =0;for(var i =0; i<1000;i++){var ss =require('net').Socket({fd:null,type:'tcp4',allowHalfOpen:false});
    ss.connect(1234,function(){
        count++;
        console.log(count);});}

 

 

posted on 2013-03-11 11:40  雨弓  阅读(2353)  评论(1编辑  收藏  举报