node将geojson转shp需要调用[ogr2ogr][1]库来实现,在调用ogr2ogr库时,因为其通过调用gdal的工具来实现将

geojson转shp,所以需要安装gdal并配置环境变量,详情可参考此链接。环境配置完,可以进行代码实现了。

首先引入ogr2ogr库
    const ogr2ogr = require('ogr2ogr')
生成shp文件压缩包
    // 声明一个geojson变量也可以是geojson文件目录    var geojson = {      type: 'FeatureCollection',      features: [        {          type: 'Feature',          geometry        }      ]    }    // shp保存目录    const zipPath = './export/shpfile.zip'    // 创建文件写入流    var file = fs.createWriteStream(zipPath)    // 调用ogr2ogr进行转化    var ogr = ogr2ogr(geojson).project('EPSG:4326')      .format('ESRI Shapefile')      .skipfailures()      .stream()    ogr.pipe(file)    
然后将shp压缩文件传给前端,这里可以通过不同的方法进行传递

(1) 通过sendFile直接进行传递

    var resPath = path.join(__dirname, '..', zipPath)    res.sendFile(resPath)

(2)通过流的方式进行传递

    var resPath = path.join(__dirname, '..', zipPath)    // 文件写入完成触发事件    file.on('finish', function() {      res.set({        'Content-Type': 'application/zip',        'Content-Disposition':          'attachment; filename=' + encodeURI(name) + '.zip',        'Content-Length': fs.statSync(zipPath).size      })      let fReadStream = fs.createReadStream(zipPath)      fReadStream.pipe(res)      fReadStream.on('end', function() {        fs.unlinkSync(resPath)      })      fReadStream.on('error', function(err) {        console.log(err)      })    })
最后是前端发送请求接收的代码
      axios.post('http://localhost:3000/jsontoshp', {        responseType: 'blob'      }).then(res => {        const blobUrl = URL.createObjectURL(res.data)        const a = document.createElement('a')        a.style.display = 'none'        a.download = '文件名称'        a.href = blobUrl        a.click()        URL.revokeObjectURL(blobUrl)      })

这里需要注意的地方是前端发送请求时需要设置一个参数responseType: 'blob',这里用到了Blob对象,这里是从服务器接收到的文件流创建blob对象并使用该blob 创建一个指向类型数组的URL,将该url作为a标签的链接目标,然后去触发a标签的点击事件从而文件下载。