const readline = require("node:readline") const fs = require('node:fs') // we will sum the last column of the CSV file let sum = 0 let isHeader = true const start = Date.now() const file = fs.createReadStream('./data.csv') // 把压缩包解压出来最大的文件改名成data.csv,方便代码编写 const lineReader = readline.createInterface({ input: file, }) lineReader .on("line", (line) => { // we need to skip the first line which is the header if (isHeader) { isHeader = false return }
// ource csv has a comma as delimiter const fields = line.trimEnd().split(",") // we get the last column and parse the value to integer const last = parseInt(fields[fields.length - 1])
// there are acouple of lines with broken values we should ignore those if (!isNaN(last)) { sum += last } }) .on("close", () => { console.log(`总共${sum}行`) console.log(`用时${(Date.now() - start) / 1000}s`,) })
use std::io::{BufRead, BufReader}; use std::fs::File; use std::time::{SystemTime}; fnmain() { letstart = SystemTime::now(); letmut sum = 0; letfile = File::open("./data.csv").expect("Unable to open file"); letreader = BufReader::new(file); letmut is_header = true; forlinein reader.lines() { letline = line.expect("Unable to read line"); if is_header { is_header = false; continue; } // we get the last column and parse the value to integer letres = line .trim_end() .split(",") .last() .unwrap() .parse::<f32>() // some values are as floats but we still parse everything to int .unwrap_or(0.0) asi64;
use std::{ fs::File, io::{self, BufRead}, path::Path, };
use napi::{bindgen_prelude::AsyncTask, JsNumber, Task};
#[macro_use] externcrate napi_derive;
// we want our function to be a promise to be executed asynchronously to not block the event loop in nodejs // and for that we need to create this weird structs AsyncReadCsv and impl the Task trait for it.
// this is the main function that receive the path to the csv file // and start processing the data line by line fnread_csv(path: String) ->i64 { letlines = read_lines(Path::new(&path)).unwrap();
letmut sum = 0;
forlinein lines { ifletOk(ip) = line { letres = ip .trim_end() .split(",") .last() .unwrap() .parse::<f32>() .unwrap_or(0.0) asi64;
sum += res; } }
sum }
// useful function to read the lines from a file fnread_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { letfile = File::open(filename)?; Ok(io::BufReader::new(file).lines()) }
在你的项目中运行npm run build后,你会得到一个index.js、index.d.ts和async_csv_reader.win32-x64-msvc.node文件,你可以从nodejs中调用它们。