Подтвердить что ты не робот

Рекомендации библиотеки: NodeJs читает CSV файл

С помощью nodejs я хочу проанализировать CSV файл из 10000 записей и выполнить некоторые операции с каждой строкой. Я пытался использовать http://www.adaltas.com/projects/node-csv. Я не мог заставить это остановиться в каждом ряду. Это просто читает все 10000 записей. Мне нужно сделать следующее

  1. читать CSV построчно
  2. выполнять трудоемкую операцию на каждой линии
  3. перейти к следующей строке

Может кто-нибудь предложить какие-либо альтернативные идеи здесь?

4b9b3361

Ответ 1

Похоже, вам нужно использовать какое-то потоковое решение, существовали уже такие библиотеки, поэтому, прежде чем изобретать себя, попробуйте эту библиотеку, которая также включает поддержку проверки. https://www.npmjs.org/package/fast-csv

Ответ 2

Мое текущее решение использует асинхронный модуль для выполнения последовательно:

var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');

var inputFile='myfile.csv';

var parser = parse({delimiter: ','}, function (err, data) {
  async.eachSeries(data, function (line, callback) {
    // do something with the line
    doSomething(line).then(function() {
      // when processing finishes invoke the callback to move to the next one
      callback();
    });
  })
});
fs.createReadStream(inputFile).pipe(parser);

Ответ 3

Я использовал этот способ: -

var fs = require('fs'); 
var parse = require('csv-parse');

var csvData=[];
fs.createReadStream(req.file.path)
    .pipe(parse({delimiter: ':'}))
    .on('data', function(csvrow) {
        console.log(csvrow);
        //do something with csvrow
        csvData.push(csvrow);        
    })
    .on('end',function() {
      //do something wiht csvData
      console.log(csvData);
    });

Ответ 4

Проект node -csv, который вы ссылаетесь, вполне достаточен для задачи преобразования каждой строки большой части данных CSV из документов: http://csv.adaltas.com/transform/:

csv()
  .from('82,Preisner,Zbigniew\n94,Gainsbourg,Serge')
  .to(console.log)
  .transform(function(row, index, callback){
    process.nextTick(function(){
      callback(null, row.reverse());
    });
});

По моему опыту, я могу сказать, что это также довольно быстрая реализация, я работал с ним на наборах данных с почти 10 тыс. записей, а время обработки на разумном уровне в десятки миллисекунд для всего набора.

Резервное предложение на основе редукции на основе юрки: node -csv IS stream based и следует API-интерфейсу Node.js '.

Ответ 5

Чтобы приостановить потоковую передачу в fast-csv, вы можете сделать следующее:

let csvstream = csv.fromPath(filePath, { headers: true })
    .on("data", function (row) {
        csvstream.pause();
        // do some heavy work
        // when done resume the stream
        csvstream.resume();
    })
    .on("end", function () {
        console.log("We are done!")
    })
    .on("error", function (error) {
        console.log(error)
    });

Ответ 6

Модуль Fast-CSV npm может считывать данные построчно из файла CSV.

Вот пример:

let csv= require('fast-csv');

var stream = fs.createReadStream("my.csv");

csv
 .fromStream(stream, {headers : true})
 .on("data", function(data){
     console.log('I am one line of data', data);
 })
 .on("end", function(){
     console.log("done");
 });

Ответ 7

  • Это решение использует csv-parser вместо csv-parse используемого в некоторых ответах выше.
  • csv-parser появился примерно через 2 года после csv-parse.
  • Они оба решают одну и ту же цель, но лично я нашел csv-parser лучше, поскольку через него легко обрабатывать заголовки.

Сначала установите csv-parser:

npm install csv-parser

Итак, предположим, что у вас есть CSV файл, как это:

NAME, AGE
Lionel Messi, 31
Andres Iniesta, 34

Вы можете выполнить необходимую операцию как:

const fs = require('fs'); 
const csv = require('csv-parser');

fs.createReadStream(inputFilePath)
.pipe(csv())
.on('data', function(data){
    try {
        console.log("Name is: "+data.NAME);
        console.log("Age is: "+data.AGE);

        //perform the operation
    }
    catch(err) {
        //error handler
    }
})
.on('end',function(){
    //some final operation
});  

Для дальнейшего чтения обратитесь

Ответ 8

Мне нужен был асинхронный CSV-ридер, и я сначала попытался ответить @Pransh Tiwari, но не смог заставить его работать с await и util.promisify(). В конце концов я наткнулся на node-csvtojson, который делает то же самое, что csv-parser, но с обещаниями. Вот пример использования csvtojson в действии:

const csvToJson = require('csvtojson');

const processRecipients = async () => {
    const recipients = await csvToJson({
        trim:true
    }).fromFile('./recipients.csv');

    // Code executes after recipients are fully loaded.
    recipients.forEach((recipient) => {
        console.log(recipient.name, recipient.email);
    });
};

Ответ 9

Попробуйте подключить плагин npm по очереди.

npm install line-by-line --save

Ответ 10

это мое решение, чтобы получить CSV файл с внешнего URL

const parse = require( 'csv-parse/lib/sync' );
const axios = require( 'axios' );
const readCSV = ( module.exports.readCSV = async ( path ) => {
try {
   const res = await axios( { url: path, method: 'GET', responseType: 'blob' } );
   let records = parse( res.data, {
      columns: true,
      skip_empty_lines: true
    } );

    return records;
 } catch ( e ) {
   console.log( 'err' );
 }

} );
readCSV('https://urltofilecsv');

Ответ 11

fs = require('fs');
fs.readFile('FILENAME WITH PATH','utf8', function(err,content){
if(err){
    console.log('error occured ' +JSON.stringify(err));
 }
 console.log('Fileconetent are ' + JSON.stringify(content));
})

Ответ 12

Вы можете конвертировать CSV в формат JSON с помощью модуля CSV-JSON, а затем вы можете легко использовать файл JSON в вашей программе

Ответ 13

Обходной путь для решения этой задачи с помощью await/async:

const csv = require('csvtojson')
const csvFilePath = 'data.csv'
const array = await csv().fromFile(csvFilePath);

Ответ 14

NPM установить CSV

Пример CSV файла Вам понадобится CSV файл для анализа, поэтому либо он у вас уже есть, либо вы можете скопировать приведенный ниже текст и вставить его в новый файл и вызвать этот файл "mycsv.csv".

ABC, 123, Fudge
532, CWE, ICECREAM
8023, POOP, DOGS
441, CHEESE, CARMEL
221, ABC, HOUSE
1
ABC, 123, Fudge
2
532, CWE, ICECREAM
3
8023, POOP, DOGS
4
441, CHEESE, CARMEL
5
221, ABC, HOUSE

Пример чтения кода и синтаксический анализ файла CSV

Создайте новый файл и вставьте в него следующий код. Обязательно прочитайте, что происходит за кулисами.

    var csv = require('csv'); 
    // loads the csv module referenced above.

    var obj = csv(); 
    // gets the csv module to access the required functionality

    function MyCSV(Fone, Ftwo, Fthree) {
        this.FieldOne = Fone;
        this.FieldTwo = Ftwo;
        this.FieldThree = Fthree;
    }; 
    // Define the MyCSV object with parameterized constructor, this will be used for storing the data read from the csv into an array of MyCSV. You will need to define each field as shown above.

    var MyData = []; 
    // MyData array will contain the data from the CSV file and it will be sent to the clients request over HTTP. 

    obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) {
        for (var index = 0; index < data.length; index++) {
            MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2]));
        }
        console.log(MyData);
    });
    //Reads the CSV file from the path you specify, and the data is stored in the array we specified using callback function.  This function iterates through an array and each line from the CSV file will be pushed as a record to another array called MyData , and logs the data into the console to ensure it worked.

var http = require('http');
//Load the http module.

var server = http.createServer(function (req, resp) {
    resp.writeHead(200, { 'content-type': 'application/json' });
    resp.end(JSON.stringify(MyData));
});
// Create a webserver with a request listener callback.  This will write the response header with the content type as json, and end the response by sending the MyData array in JSON format.

server.listen(8080);
// Tells the webserver to listen on port 8080(obviously this may be whatever port you want.)
1
var csv = require('csv'); 
2
// loads the csv module referenced above.
3
​
4
var obj = csv(); 
5
// gets the csv module to access the required functionality
6
​
7
function MyCSV(Fone, Ftwo, Fthree) {
8
    this.FieldOne = Fone;
9
    this.FieldTwo = Ftwo;
10
    this.FieldThree = Fthree;
11
}; 
12
// Define the MyCSV object with parameterized constructor, this will be used for storing the data read from the csv into an array of MyCSV. You will need to define each field as shown above.
13
​
14
var MyData = []; 
15
// MyData array will contain the data from the CSV file and it will be sent to the clients request over HTTP. 
16
​
17
obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) {
18
    for (var index = 0; index < data.length; index++) {
19
        MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2]));
20
    }
21
    console.log(MyData);
22
});
23
//Reads the CSV file from the path you specify, and the data is stored in the array we specified using callback function.  This function iterates through an array and each line from the CSV file will be pushed as a record to another array called MyData , and logs the data into the console to ensure it worked.
24
​
25
var http = require('http');
26
//Load the http module.
27
​
28
var server = http.createServer(function (req, resp) {
29
    resp.writeHead(200, { 'content-type': 'application/json' });
30
    resp.end(JSON.stringify(MyData));
31
});
32
// Create a webserver with a request listener callback.  This will write the response header with the content type as json, and end the response by sending the MyData array in JSON format.
33
​
34
server.listen(8080);
35
// Tells the webserver to listen on port 8080(obviously this may be whatever port you want.)
Things to be aware of in your app.js code
In lines 7 through 11, we define the function called 'MyCSV' and the field names.

If your CSV file has multiple columns make sure you define this correctly to match your file.

On line 17 we define the location of the CSV file of which we are loading.  Make sure you use the correct path here.

Запустите приложение и проверьте функциональность Откройте консоль и введите следующую команду:

Node app 1 Node app Вы должны увидеть следующий вывод в вашей консоли:

[  MYCSV { Fieldone: 'ABC', Fieldtwo: '123', Fieldthree: 'Fudge' },
   MYCSV { Fieldone: '532', Fieldtwo: 'CWE', Fieldthree: 'ICECREAM' },
   MYCSV { Fieldone: '8023', Fieldtwo: 'POOP', Fieldthree: 'DOGS' },
   MYCSV { Fieldone: '441', Fieldtwo: 'CHEESE', Fieldthree: 'CARMEL' },
   MYCSV { Fieldone: '221', Fieldtwo: 'ABC', Fieldthree: 'HOUSE' }, ]

1 [MYCSV {Fieldone: 'ABC', Fieldtwo: '123', Fieldthree: 'Fudge'}, 2 MYCSV {Fieldone: '532', Fieldtwo: 'CWE', Fieldthree: 'ICECREAM'}, 3 MYCSV {Fieldone: '8023', Fieldtwo: 'POOP', Fieldthree: 'DOGS'}, 4 MYCSV {Fieldone: '441', Fieldtwo: 'CHEESE', Fieldthree: 'CARMEL'}, 5 MYCSV {Fieldone: '221', Fieldtwo: 'ABC', Fieldthree: 'HOUSE'},] Теперь вы должны открыть веб-браузер и перейти на свой сервер. Вы должны увидеть, как он выводит данные в формате JSON.

Заключение Используя node.js и его CSV-модуль, мы можем быстро и легко читать и использовать данные, хранящиеся на сервере, и делать их доступными для клиента по запросу.