浅析Node.js查找字符串功能(2)

var fs = require('fs'); fs.open('./my_file.txt', 'a', function opened(err, fd) { if (err) { throw err; } var writeBuffer = new Buffer('hello, world!'), bufferPosition = 0, bufferLength = writeBuffer.length, filePosition = null; fs.write( fd, writeBuffer, bufferPosition, bufferLength, filePosition, function(err, written) { if (err) { throw err; } console.log('wrote ' + written + ' bytes'); }); });

对于文件的读写操作,我们不应该忘记在这些操作都完成之后执行关闭操作,即close(); 下面是一个封装的方法,其中就包括了文件的后期关闭操作,使用起来方便:

var fs = require('fs'); function openAndWriteToSystemLog(writeBuffer, callback) { fs.open('./my_file', 'a', function(err, fd) { if (err) { return callback(err); } function notifyError(err) { fs.close(fd, function() { callback(err); }); } var bufferOffset = 0, bufferLength = writeBuffer.length, filePosition = null; fs.write( fd, writeBuffer, bufferOffset, bufferLength, filePosition,function(err, written) { if (err) { return notifyError(err); } fs.close(fd, function() { callback(err); }); }); }); } openAndWriteToSystemLog(new Buffer('writing this string'),function(err) { if (err) { console.log("error while opening and writing:", err.message); return; } console.log('All done with no errors'); });

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgsxsp.html