forked from teamzerolabs/node-csv-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
77 lines (62 loc) · 1.87 KB
/
main.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Shows how to parse existing csv files into node data structure
// Source: https://support.spatialkey.com/spatialkey-sample-csv-data/
console.log(`Hello, in this script, we will:
1. load data from Sacramentorealestatetransactions.csv
2. Parse it into json record (input)
3. Write it back out into another csv file (output)`);
// Input
const neatCsv = require("neat-csv");
// https://mircozeiss.com/json2csv/
const { parseAsync } = require("json2csv");
const fs = require("fs");
const csv = fs.readFileSync("./Sacramentorealestatetransactions.csv");
async function readCSV() {
return neatCsv(csv);
}
async function main() {
const result = await readCSV();
// Uncomment this line to see what an individual record looks like.
// console.log(result);
/*
An array of object record like the following:
{ street: '4900 71ST ST',
city: 'SACRAMENTO',
zip: '95820',
state: 'CA',
beds: '3',
baths: '1',
sq__ft: '1018',
type: 'Residential',
sale_date: 'Wed May 21 00:00:00 EDT 2008',
price: '260014',
latitude: '38.53151',
longitude: '-121.421089' }
*/
result.forEach(record => {
record.zip = parseFloat(record.zip);
record.sq__ft = parseFloat(record.sq__ft);
record.baths = parseFloat(record.baths);
record.beds = parseFloat(record.beds);
record.price = parseFloat(record.price);
record.latitude = parseFloat(record.latitude);
record.longitude = parseFloat(record.longitude);
});
// Next we will convert it back into a csv file.
// Let's keep only sqft, price, and zip
const fields = [
"zip",
{
label: "sqft",
value: "sq__ft"
},
"price"
];
const opts = { fields };
const resultCSV = await parseAsync(result, opts);
fs.writeFileSync("./cleanedup.csv", resultCSV);
}
main()
.then(() => console.log("All done!"))
.catch(err => {
console.error(err.message);
});