【问题标题】:reading and writing a large txt file in node.js causing exception在 node.js 中读取和写入一个大的 txt 文件导致异常
【发布时间】: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


    【解决方案1】:

    您使用的所有fs 函数都是异步的,因此您实际上是在尝试同时打开数千次copy.txt

    您似乎也从未更新 bytesRead,因此您的 while 循环将永远运行。

    【讨论】:

    • 好吧,我已经更改了一些代码并确保 copy.txt 只打开一次,但我必须以异步方式工作,这样我的主线程就不会阻塞。仍然出现异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多