我必須逐行讀取一個大的 .csv 檔案,然后從作為國家的檔案中取出第一列并計算重復項。例如,如果檔案包含:
USA
UK
USA
輸出應該是:
USA - 2
UK -1
代碼:
const fs = require('fs')
const readline = require('readline')
const file = readline.createInterface({
input: fs.createReadStream('file.csv'),
output: process.stdout,
terminal: false
})
file.on('line', line => {
const country = line.split(",", 1)
const number = ??? // don't know how to check duplicates
const result = country number
if(lineCount >= 1 && country != `""`) {
console.log(result)
}
lineCount
})
uj5u.com熱心網友回復:
因此,對于初學者來說, Array.prototype.split 回傳一個陣列,您似乎希望在拆分陣列時獲得陣列中的第一個值,因為您將其限制為一個。你可以在這里閱讀它:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
接下來,您可以創建所有國家/地區的地圖,并存盤它們被看到的次數,然后在檔案讀取完畢后記錄結果
const countries = {}
let lineCount = 0
file.on('line', line => {
// Destructure the array and grab the first value
const [country] = line.split(",", 1)
// Calling trim on the country should remove outer white space
if (lineCount >= 1 && country.trim() !== "") {
// If the country is not in the map, then store it
if (!countries[country]) {
countries[country] = 1
} else {
countries[country]
}
}
lineCount
})
// Add another event listener for when the file has finished being read
// You may access the country data here, since this callback function
// won't be called till the file has been read
// https://nodejs.org/api/readline.html#event-close
file.on('close', () => {
for (const country in countries) {
console.log(`${country} - ${countries[country]}`)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395851.html
標籤:javascript 节点.js 溪流 FS 阅读线
