aboutsummaryrefslogtreecommitdiff
path: root/bin/id.js
blob: de60e9994db8099e21d172aaf53a23f394a9d352 (plain) (blame)
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
#!/usr/bin/env node

/**
 * Set GeoJSON id
 */

const fs = require('fs')
const { Transform, pipeline } = require('stream')
const ndjson = require('ndjson')

const argv = require('yargs/yargs')(process.argv.slice(2))
  .option('property', {
    type: 'boolean',
    description: 'Also set id as a property'
  })
  .argv

if (argv._.length < 2) {
  console.error("Usage: ./id.js input.geojson output.geojson")
  process.exit(1)
}

const inputFile = argv._[0]
const outputFile = argv._[1]

if (!fs.existsSync(inputFile)) {
  console.error(`${inputFile} not found`)
  process.exit(1)
}

let index = 0
const id = new Transform({
  readableObjectMode: true,
  writableObjectMode: true,
  transform(feature, encoding, callback) {
    index++

    if (process.stdout.isTTY && index % 10000 === 0) {
      process.stdout.write(` ${index.toLocaleString()}\r`)
    }

    feature.id = index

    if (argv.property) {
      feature.properties.id = index
    }

    this.push(feature)

    callback()
  }
})

pipeline(
  fs.createReadStream(inputFile),
  ndjson.parse(),
  id,
  ndjson.stringify(),
  fs.createWriteStream(outputFile),
  err => {
    if (err) {
      console.log(err)
      process.exit(1)
    } else {
      process.exit(0)
    }
  }
)