This repository was archived by the owner on Jan 30, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimport-csv.ts
More file actions
64 lines (55 loc) · 1.89 KB
/
import-csv.ts
File metadata and controls
64 lines (55 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import fs from 'fs';
import readline from 'readline';
/**
* Asynchronously opens a CSV file and reads the column names.
* @param filePath The path to the CSV file.
* @returns A promise with an array of column names.
*/
async function readColumnNames(filePath: string): Promise<string[]> {
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
const firstLine = await new Promise<string>((resolve, reject) => {
rl.on('line', (line) => {
rl.close(); // Close after reading the first line
resolve(line);
});
rl.on('error', reject);
});
return firstLine.split(','); // Assumes that the column names are comma-separated
}
/**
* Converts a CSV line into an object using the provided column names.
* @param line A line from the CSV file.
* @param columnNames An array of column names.
* @returns An object representing the record.
*/
function parseSingleRecord(line: string, columnNames: string[]): Record<string, any> {
const values = line.split(',');
const record: Record<string, any> = {};
columnNames.forEach((columnName, index) => {
record[columnName] = values[index];
});
return record;
}
function processSingleRecord(record: any, columnNames) {
record = parseSingleRecord(record, columnNames);
// Apply any transformation logic here
return record;
}
// Example usage
const filePath = 'path_to_your_file.csv'; // Change to your file path
async function processInput() {
const columnNames = await readColumnNames(filePath);
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
rl.on('line', (line) => {
const record = processSingleRecord(line, columnNames);
console.log(record);
});
}