【发布时间】:2015-10-30 11:15:08
【问题描述】:
我有一个大约 1GB 的大 txt 文件。我正在尝试从此文件中读取内容并写入另一个文件。我的代码是 -->
var fs = require("fs");
var fb = fs.openSync('./copy.txt','r+');
fs.open('./largefile.txt','r',function(error,fd){
fs.fstat(fd,function(error,stats){
var totalFileSize = stats.size,
chunk = 512,
buffer = new Buffer(512),
bytesRead = 0;
while(bytesRead < totalFileSize){
if((totalFileSize - bytesRead) < chunk){
chunk = totalFileSize - bytesRead ;
}
fs.read(fd,buffer,0,chunk,bytesRead,function(err, bytesRead, buffer){
fs.write(fb,buffer,0,chunk,bytesRead,function(err,written,buffer){});
});
bytesRead = bytesRead + chunk;
}
});
});
我收到了这个错误控制台 ->
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory
Q1) 我可能做错了什么?
Q2) 在 child_process 中这样做有什么好处吗?如果是,我应该使用 fork() 还是 spawn() 以及如何使用?(我是 node.js 的新手,发现 child_process 很混乱。)
【问题讨论】:
标签: node.js multithreading io child-process