all files / ogr2ogr/modules/ csv.js

97.5% Statements 39/40
87.5% Branches 14/16
100% Functions 8/8
100% Lines 38/38
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                                 72× 72×                                        
var fs = require('fs')
var path = require('path')
var CSV = require('comma-separated-values')
var util = require('./util')
 
var BASE_VRT = '<OGRVRTDataSource>\n\
                  <OGRVRTLayer name="{{name}}">\n\
                    <SrcDataSource>{{file}}</SrcDataSource>\n\
                    <GeometryType>wkbUnknown</GeometryType>\n\
                    <GeometryField encoding="{{enc}}" {{encopt}} />\n\
                  </OGRVRTLayer>\n\
                </OGRVRTDataSource>'
 
var extractHead = function(fpath, cb) {
  var sf = fs.createReadStream(fpath)
  var one = util.oneCallback(cb)
  var data = ''
  sf.on('data', function(chunk) {
    data += chunk
    Eif (data) {
      sf.pause()
      sf.destroy()
      sf.emit('end')
    }
  })
  sf.on('error', one)
  sf.on('end', util.oneCallback(function() {
    CSV.forEach(data.split(/(?:\n|\r\n|\r)/g).shift(), function(head) {
      one(null, head)
    })
    // if there is nothing to parse
    one()
  }))
}
 
exports.makeVrt = function(fpath, cb) {
  extractHead(fpath, function(er, headers) {
    Iif (er) return cb(er)
 
    var geo = {}
    headers.forEach(function(header) {
      var ht = (String(header)).trim()
      switch (true) {
      case /\b(lon|longitude|lng|x)\b/i.test(ht):
        geo.x = header
        break
      case /\b(lat|latitude|y)\b/i.test(ht):
        geo.y = header
        break
      case /\b(the_geom|geom)\b/i.test(ht):
        geo.geom = header
        break
      default:
      }
    })
 
    if (!geo.geom && !geo.x) return cb(null, fpath) // no geometry fields, parse attributes
 
    var vrtData = util.tmpl(BASE_VRT, {
      file: fpath,
      name: path.basename(fpath, '.csv'),
      enc: geo.geom ? 'WKT' : 'PointFromColumns',
      encopt: geo.geom
        ? 'field="' + geo.geom + '"'
        : 'x="' + geo.x + '" y="' + geo.y + '"',
    })
 
    var vrtPath = util.genTmpPath() + '.vrt'
    return fs.writeFile(vrtPath, vrtData, function(er2) {
      cb(er2, vrtPath)
    })
  })
}