【问题标题】:Im Unable to Write a txt File using fs on Nodejs ,can Somebody Help me?我无法在 Node Js 中使用 fs 编写文本文件,有人可以帮助我吗?
【发布时间】:2017-06-03 16:12:45
【问题描述】:

我尝试在 Nodejs 上使用 Fs 编写一个 txt 文件,但出现以下错误。

call_and_retry_last 分配失败 - 进程内存不足

这是我正在使用的代码:

UserPayment.find({} ,function (error , usersdata){
  count=usersdata.length;
  usersdata.forEach(function(user){
     sum+=user.Amount;
     fs.appendFile('unapec-appap.txt', 'D'+padding(user.Id,13)+user.IdType+padding(user.Account,15)+padding(user.Amount,20),function (err) {
        console.log(err);
     });
  });
  callback();
});

UserPayment 是使用 mongoose 调用 mongolab 数据库

【问题讨论】:

  • fs.appendFileasync

标签: javascript node.js mongodb asynchronous mongoose


【解决方案1】:

你不应该对大数据使用 Array.forEach 函数。此外,forEach 函数会阻塞代码,并且在大多数情况下无法与 node 一起按预期工作,这在很大程度上基于非阻塞代码(异步代码)。

您可以尝试“async”库,它对异步 javascript 编程具有非常有用的功能。

对于这种情况,请以如下方式使用 Async.Each 函数:

async.each(arrayofusers, appendfilesfunction, function(err){
  // if any of the saves produced an error, err would equal that error
});

针对您的特定问题:

var async = require('async');

UserPayment.find({} ,function (error , usersdata){
    count=usersdata.length;

    async.each(userdata, function(user,next){
        sum+=user.Amount;
        fs.appendFile('unapec-appap.txt', 'D'+padding(user.Id,13)+user.IdType+padding(user.Account,15)+padding(user.Amount,20)
                      ,function (err) {
                          if(err) return next(err); 
                          next();
         });
    }, function(err){
        if(err) console.log(err); // All errors will be handled here
    });


});

【讨论】:

    【解决方案2】:

    你可以async逐行追加。

    var async = require("async");
    
    UserPayment.find({} ,function (error , usersdata){
      count=usersdata.length;
      async.each(usersdata, function(user, cb){
        sum+=user.Amount;
    
        fs.appendFile('unapec-appap.txt', 'D'+padding(user.Id,13)+user.IdType+padding(user.Account,15) + padding(user.Amount,20), function (err) {
            cb();
        });
      }, function(err){
        callback();
      })
    });
    

    【讨论】:

      猜你喜欢
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多