Понимание узла / обещания при чтении csv в массив (получение значений из обещания) - PullRequest
0 голосов
/ 23 октября 2019

Я хочу прочитать файл .csv в массив, получить количество прочитанных строк и отправить массив другой функции для дополнительной обработки.

Я искал и нашел пример кода, который работает (кроме возможности получить значения из обещания).

const csv = require('csv-parser')

async function readCsv(csv_file_path) {

    const list = []     // read .csv into array (list)
    var num_rows = 0    // the number of rows read

    fs.createReadStream(csv_file)
        .pipe(csv())
        .on('data', (data) => list.push(data))
        .on('end', () => {
            num_rows = list.length
            console.log('num_rows', num_rows) // prints num rows read, fine
        })

    // now, here, at this point in the code, I want to use:
    //  1. num_rows
    //  2. address_list outside fo the fs.createReadStream function
    // how do I do this?

    // Here, outside, num_rows is 0, and nothing is in the list
    console.log('num_rows:', num_rows)
    for (let address of address_list) {
        console.log('address:', address);
    }

    // how do I get the value for num_rows, and contents of list[] set,
    // so I can use here at this point in the code?
}

1 Ответ

0 голосов
/ 23 октября 2019

Я предлагаю вам использовать библиотеку для .csv разбора. Хороший - csv-parse, вы можете установить его, используя npm.

Вот простой пример использования синхронного API.

const parse = require('csv-parse/lib/sync')

const input = `
"key_1","key_2"
"value 1","value 2"
"value 3","value 3"
`
const records = parse(input, {
  skip_empty_lines: true
})

console.log(records)

// Output:
// [ [ 'key_1', 'key_2' ],
// [ 'value 1', 'value 2' ],
// [ 'value 3', 'value 3' ] ]
// Just get the length of the output array to get the number of rows in the file

Документацию по API можно найти здесь .

...