-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2db.js
51 lines (46 loc) · 1.71 KB
/
csv2db.js
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
const fs = require('fs');
const csv = require('csv-parser');
function csvToJson(csvFilePath, jsonFilePath) {
return new Promise((resolve, reject) => {
const results = { stocks: [] };
let lineCount = 0;
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('data', (row) => {
lineCount++;
const symbol = row['SYMBOL'] ? String(row['SYMBOL']).trim() : null;
const companyName = row['NAME OF COMPANY'] ? String(row['NAME OF COMPANY']).trim() : null;
if (symbol && companyName) {
results.stocks.push({
ticker: symbol,
name: companyName,
});
console.log(`Converted: ${symbol} - ${companyName}`);
}
})
.on('end', () => {
console.log(`Total number of lines: ${lineCount}`);
fs.writeFile(jsonFilePath, JSON.stringify(results, null, 4), (err) => {
if (err) {
reject(`Error writing to JSON file: ${err}`);
} else {
console.log(`Successfully converted '${csvFilePath}' to '${jsonFilePath}'`);
resolve();
}
});
})
.on('error', (err) => {
reject(`Error reading or parsing CSV file: ${err}`);
});
});
}
// Example Usage:
const csvFile = 'EQUITY_L.csv';
const jsonFile = 'db.json';
csvToJson(csvFile, jsonFile)
.then(() => {
console.log("Conversion Complete");
})
.catch((error) => {
console.error("Error during conversion:", error);
});