使用node-csv和meteor文件将CSV导入集合 [英] Using node-csv and meteor-file to import CSV into a collection

查看:154
本文介绍了使用node-csv和meteor文件将CSV导入集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在试图导入CSV,并使用 meteor-file 从客户端上传,并使用 node-csv 服务器端将其转换为CSV。我基本上需要从用户上传的CSV文件中填充数据。



/server/filehandler.js:

  Meteor.methods({
'uploadFile':function(file){

if .start === 0){
console.log(file.name);
console.log(file.type);
console.log(file.size);
}

file.save('/ home / russell / tmp',{});
var buffer = new Buffer(file.data);
CSV from(
buffer.toString(),
{comment:'#',delimiter:',',quote:''}

.to.array数据){
//console.log(data);

for(var row = 0; row< data.length; row ++){
console.log row'];
newRecord = {
'firstname':data [row] [0],
'lastname':data [row] :data [row] [2],
'emailshort':data [row] [3],
'emailmain':data [row] [row] [5]
};
console.log(newRecord);
reas.insert(newRecord); // *** _dynamic_meteor ERROR这里!
}
});

} // uploadFile
});

console.log告诉我CSV到数组的转换是很好的。



集合 reas 在/lib/models.js - / lib中设置为集合,与/ server& / client。



我试过在Meteor.method()之外有一个全局变量,并将转换结果存储在那里,我也试过使用Session.set(),但我只是不能得到转换的结果,在方法()之外。



谢谢。 p>

UPDATED - 2013-10-11



我的/libs/models.js看起来像这样:

  reas = new Meteor.Collection(RegisteredEmailAddresses); 

/ *检查当前请求更新的用户是否是admin用户* /
function adminUser(userId){
var adminUser = Meteor.users.findOne ({username:admin});
return(userId&& adminUser&&&userid === adminUser._id);
}

reas.allow({
insert:function(userId,doc){
return adminUser(userId);
},
update:function(userId,docs,fields,modifier){
return adminUser(userId);
},
remove:function(userId,docs){
return adminUser userId);
}
});

EUREKA MOMENT?!



不应该是 / lib 不是/ libs?



更新日期2013-10-09



如果我离开

  reas.insert(newRecord); 

我收到以下错误讯息。



错误讯息:

  W2036-20:56:29.463(1)? (STDERR)packages / mongo-livedata.js:1862 
W2036-20:56:29.471(1)? (STDERR)throw e;
W2036-20:56:29.475(1)? (STDERR)^
W2036-20:56:29.953(1)? (STDERR)错误:流星代码必须始终在光纤内运行。尝试使用Meteor.bindEnvironment包装您传递给非Meteor库的回调。
W2036-20:56:29.958(1)? (STDERR)在Object.Meteor.bindEnvironment(packages / meteor / dynamics_nodejs.js:60)
W2036-20:56:29.958(1)? (STDERR)at null。< anonymous> (packages / meteor / helpers.js:108)
W2036-20:56:29.959(1)? (STDERR)在MongoConnection。(匿名函数)[插入](包/ mongo-livedata / mongo_driver.js:491)
W2036-20:56:29.964(1)? (STDERR)在Meteor.Collection(匿名函数)[插入](包/ mongo-livedata / collection.js:448)
W2036-20:56:29.965(1)? (STDERR)at app / server / server.js:37:20
W2036-20:56:29.966(1)? (STDERR)at null。< anonymous> (/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/to.js:274:14)
W2036-20:56:29.967(1)? (STDERR)at EventEmitter.emit(events.js:95:17)
W2036-20:56:29.971(1)? (STDERR)at null。< anonymous> (/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/index.js:214:17)
W2036-20:56:29.972(1)? (STDERR)at EventEmitter.emit(events.js:92:17)
W2036-20:56:29.975(1)? (STDERR)在Transformer.end(/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/transformer.js:241 :17)


解决方案

使用回调并运行异步代码,我需要使用未来。有关详情,请参阅 http://gist.io/3443021



这里是我的工作代码:

  Meteor.methods({
'uploadFile':function

Future = Npm.require('fibers / future');

console.log(file.name +'\'+ file.type +'\'+ file .size);

file.save('/ home / russell / tmp',{});
var buffer = new Buffer(file.data);


//设置未来
var fut = new Future();

//将缓冲区(CSV文件)转换为数组
CSV ).from(
buffer.toString(),
{comment:'#',delimiter:',',quote:''}

.to.array function(data){

var newRecords = [];

for(var row = 0; row< data.length; row ++){
console.log (data [row]);
newRecord = {
'firstname':data [row] [0],
'lastname':data [row] [1],
'email':data [row ] [2],
'emailshort':data [row] [3],
'emailmain':data [row] [4] 5]
};

//console.log(newRecord);
newRecords.push(newRecord);
}

//在CSV回调结束处
//通过Future返回newRecords
fut ['return'](newRecords);
});


//等待转换结果
results = fut.wait();
console.log('results ================');
console.log(results);

//现在从文件中插入新的记录到我们的集合
if(results.length){
for(i in results){
reas.insert (results [i]);
}
}

console.log('reas现在看起来像=====================') ;
console.log(reas.find({})。fetch());

} // uploadFile

});


Been struggling for several hours now trying to import CSV, uploaded from client using meteor-file and converted to CSV using node-csv server-side. I basically need to populate my collection with data from a CSV file uploaded by the user.

/server/filehandler.js:

Meteor.methods({
'uploadFile': function (file) {

  if(file.start === 0) {
    console.log(file.name);
    console.log(file.type);
    console.log(file.size);            
  }

  file.save('/home/russell/tmp',{});
  var buffer = new Buffer(file.data);
  CSV().from(
          buffer.toString(),
          {comment: '#', delimiter: ',', quote: ''} 
      )
        .to.array( function(data){
          //console.log(data);

          for(var row=0; row<data.length; row++) {
              console.log(data[row]);
             newRecord = {
                  'firstname': data[row][0],
                  'lastname': data[row][1],
                  'email': data[row][2],
                  'emailshort': data[row][3],
                  'emailmain': data[row][4],
                  'domain': data[row][5]
              };
              console.log(newRecord);
              reas.insert(newRecord); // *** _dynamic_meteor ERROR here!
          }
        } );

 } // uploadFile
});

The console.log tells me that the CSV to array conversion is fine.

Collection reas is setup as a Collection in /lib/models.js - /lib is at the same level as /server & /client.

I've tried having a global variable outside of the Meteor.method() and storing the result of the conversion into that, and I've also tried using a Session.set(), but I just can't seem to get at the results of the conversion, outside of the method().

thanks.

UPDATED - 2013-10-11

My /libs/models.js looks like this:

reas = new Meteor.Collection("RegisteredEmailAddresses");

/*checks to see if the current user making the request to update is the admin user */
function adminUser(userId) {
    var adminUser = Meteor.users.findOne({username:"admin"});
                return (userId && adminUser && userId === adminUser._id);
            }

reas.allow({
    insert: function(userId, doc){
                        return adminUser(userId);
                    },
    update: function(userId, docs, fields, modifier){
                        return adminUser(userId);
                    },
    remove: function (userId, docs){
                        return adminUser(userId);
                    }
});

EUREKA MOMENT?!

Shouldn't that be /lib not /libs? Maybe reas is not being defined in time?

Updated 2013-10-09

If I leave in the line

reas.insert(newRecord);

I get the error message below. If I remove that line, i don't.

Error message:

W2036-20:56:29.463(1)? (STDERR) packages/mongo-livedata.js:1862
W2036-20:56:29.471(1)? (STDERR)         throw e;                                                              
W2036-20:56:29.475(1)? (STDERR)               ^
W2036-20:56:29.953(1)? (STDERR) Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
W2036-20:56:29.958(1)? (STDERR)     at Object.Meteor.bindEnvironment (packages/meteor/dynamics_nodejs.js:60)
W2036-20:56:29.958(1)? (STDERR)     at null.<anonymous> (packages/meteor/helpers.js:108)
W2036-20:56:29.959(1)? (STDERR)     at MongoConnection.(anonymous function) [as insert] (packages/mongo-livedata/mongo_driver.js:491)
W2036-20:56:29.964(1)? (STDERR)     at Meteor.Collection.(anonymous function) [as insert] (packages/mongo-livedata/collection.js:448)
W2036-20:56:29.965(1)? (STDERR)     at app/server/server.js:37:20
W2036-20:56:29.966(1)? (STDERR)     at null.<anonymous> (/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/to.js:274:14)
W2036-20:56:29.967(1)? (STDERR)     at EventEmitter.emit (events.js:95:17)
W2036-20:56:29.971(1)? (STDERR)     at null.<anonymous> (/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/index.js:214:17)
W2036-20:56:29.972(1)? (STDERR)     at EventEmitter.emit (events.js:92:17)
W2036-20:56:29.975(1)? (STDERR)     at Transformer.end (/home/russell/.meteorite/packages/node-csv-npm/Dsyko/meteor-node-csv/01be0e3e834a4f033121cb3fcc92c2697741170d/.build/npm/node_modules/csv/lib/transformer.js:241:17)

解决方案

So it turns out because CSV() uses a callback and runs Asynchronous code, I needed to use a 'Future'. For more explaination see http://gist.io/3443021

here's my working code:

Meteor.methods({
     'uploadFile': function (file) {

      Future = Npm.require('fibers/future');

      console.log(file.name+'\'+file.type+'\'+file.size);                       

      file.save('/home/russell/tmp',{});
      var buffer = new Buffer(file.data);


      // Set up the Future
      var fut = new Future(); 

      // Convert buffer (a CSV file) to an array
      CSV().from(
                   buffer.toString(),
                   {comment: '#', delimiter: ',', quote: ''} 
                )
           .to.array( function(data){

                                       var newRecords=[];

                                       for(var row=0; row<data.length; row++) {
                                         console.log(data[row]);
                                         newRecord = {
                                                       'firstname': data[row][0],
                                                       'lastname': data[row][1],
                                                       'email': data[row][2],
                                                       'emailshort': data[row][3],
                                                       'emailmain': data[row][4],
                                                       'domain': data[row][5]
                                                     };

                                         //console.log(newRecord);
                                         newRecords.push(newRecord);
                                  }

                                  // at the end of the CSV callback
                                  // return newRecords via the Future
                                  fut['return'](newRecords);
    } );


    // Wait for the results of the conversion
    results = fut.wait();
    console.log('results================');
    console.log(results);

    // now insert the new records from the file into our collectiion
    if (results.length) {
        for(i in results) {
            reas.insert(results[i]);
        }
    }

    console.log('reas now looks like =====================');
    console.log(reas.find({}).fetch());

} // uploadFile

});

这篇关于使用node-csv和meteor文件将CSV导入集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆