forked from datagouv/dvf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorate-csv-with-lat-long.js
88 lines (68 loc) · 2.25 KB
/
decorate-csv-with-lat-long.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
78
79
80
81
82
83
84
85
86
87
const csv = require('csv-parser')
const fs = require('fs')
const readline = require('readline')
const processFileToDecorateLineByLine = (fileToDecorate, lineProcessor) => {
const decoratedLines = []
const readLineInterface = readline.createInterface({
input: fs.createReadStream(fileToDecorate),
console: false
})
readLineInterface.on('line', function (line) {
decoratedLines.push(lineProcessor(line))
})
return new Promise((resolve, reject) => {
readLineInterface.on('close', () => {
resolve(decoratedLines)
})
})
}
const readLonLatByParcelId = (file) => {
const parcelsLonLat = {}
const stream = fs.createReadStream(file)
.pipe(csv({headers: ['parcel', 'date', 'department', 'lon', 'lat']}))
.on('data', (parcel) => {
parcelsLonLat[parcel.parcel] = {
lon: parcel.lon,
lat: parcel.lat
}
})
return new Promise((resolve, reject) => {
stream.on('end', () => {
resolve(parcelsLonLat)
})
stream.on('error', reject)
})
}
const main = async () => {
const args = process.argv.slice(2)
if (args.length !== 2) {
console.error("Requires 2 parameters: file-to-decorate.csv parcels-matches-lon-lat.csv")
process.exit(1)
return
}
const fileToDecorate = args[0]
const parcelsLonLatFile = args[1]
const lonLatByParcelId = await readLonLatByParcelId(parcelsLonLatFile)
const decoratedLines = await processFileToDecorateLineByLine(fileToDecorate, (line) => {
if (!line.match(/^.*,,$/)) {
return line
}
const parcelId = line.split(',')[15]
const lonLat = lonLatByParcelId[parcelId]
if (!lonLat) {
return line
}
return line.replace(/(.*),,$/, `$1,${lonLat.lon},${lonLat.lat}`)
})
const newDecoratedFile = fileToDecorate.replace(/(.*)\.csv/, '$1-decorated.csv')
const file = fs.createWriteStream(newDecoratedFile)
decoratedLines.forEach((decoratedLine) => {
file.write(decoratedLine + '\n')
})
file.end()
console.log(`Generated ${newDecoratedFile}.`)
}
main().catch(error => {
console.error(error)
process.exit(1)
})