在 node.js 中读取和写入大型 txt 文件导致异常
reading and writing a large txt file in node.js causing exception
我有一个大约 ~ 1GB 的大型 txt 文件。我试图从这个文件中读取内容并写入另一个 file.My 代码是 -->
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 很漂亮令人困惑。)
您使用的所有 fs
函数都是异步的,因此您实际上是在尝试同时打开 copy.txt
数千次。
看起来你也从不更新 bytesRead
所以你的 while 循环将永远 运行。
我有一个大约 ~ 1GB 的大型 txt 文件。我试图从这个文件中读取内容并写入另一个 file.My 代码是 -->
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 很漂亮令人困惑。)
您使用的所有 fs
函数都是异步的,因此您实际上是在尝试同时打开 copy.txt
数千次。
看起来你也从不更新 bytesRead
所以你的 while 循环将永远 运行。