遍历Node.js中CSV文件中的单元格 [英] Iterate over cells in a CSV file in Node.js

查看:74
本文介绍了遍历Node.js中CSV文件中的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件:"myCSV.csv"有两列:第一"和第二".

I have a CSV file: "myCSV.csv" with two columns: "first" and "second".

里面的所有数据都是数字.所以文件看起来像这样:

All the data inside is just numbers. So the file looks like this:

first, second
138901801, 849043027
389023890, 382903205
749029820, 317891093
...

我想遍历这些数字并对它们进行一些自定义解析,然后将结果存储在数组中.

I would like to iterate over these numbers and perform some custom parsing on them, then store results in an array.

如何实现以下行为?

const parsedData = [];

for (const row of file) {
  parsedData.push(row[0].toString() + row[1].toString());
}

推荐答案

如果使用的是用户在浏览器中选择的文件,则可以创建FileReader来响应用户的操作.(请参见 FileReader-MDN .)

If you're working with a file the user has selected in the browser, you'd make a FileReader in response to the user's action. (See FileReader - MDN.)

但是听起来您的服务器上已经有文件,在这种情况下,您将使用Node的内置文件系统模块.(请参见文件系统-NodeJS .)

But it sounds like you already have the file on your server, in which case you'd use Node's built-in File System module. (See File System - NodeJS.)

如果只需要模块的 readFile 函数,则需要在文件中使用它,例如:

If you just want the module's readFile function, you'd require it in your file like:

const {readFile} = require("fs");

您将使用它来处理文本文件,例如:

And you'd use it to process a text file like:

readFile("myFile.txt", "utf8", (error, textContent) => {
  if(error){ throw error; }
  const parsedData = [];
  for(let row of textContent.split("\n")){
    const rowItems = row.split(",");
    parsedData.push(rowItems[0].toString() + rowItems[1].toString());
  }
}

(请参阅 Node.js-雄辩的JavaScript ).

但是,如果要直接将CSV作为二进制数据处理(而不是在读取之前转换为文本文件),则需要在调用 readFile 之前添加如下内容:

However, if you want to handle your CSV directly as binary data (rather than converting to a text file before reading), you'd need to add something like this before invoking readFile:

const textContent = String.fromCharCode.apply(null, new Uint16Array(buffer));

...,其中箭头函数中的 textContent 参数由 buffer 参数代替,用于处理二进制数据.
(如果 Uint16Array 的大小错误,则可能是 Uint8Array .请参阅

...with the textContent parameter in the arrow function replaced by a buffer parameter to handle the binary data.
(If Uint16Array is the wrong size, it might be Uint8Array instead. See Buffer to String - Google.)

您可能还会发现这些资源很有帮助:
JS CSV教程-SeegateSite
JS阅读文本演示-GeeksForGeeks

You might also find these resources helpful:
JS CSV Tutorial - SeegateSite
JS read-text demo - GeeksForGeeks

这篇关于遍历Node.js中CSV文件中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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