我正在努力阅读Node.js / express.js中的geojson文件。我正在读“output.geojson” 我不想使用JSON.parse.But我想使用express.js加载它(或者至少在这个函数中使用json渲染)
var o = require('output.geojson');
app.get('/points.geojson', function(req, res) {
res.json(o);
console.log(res)
});
但是我收到了这个错误:
Users/macbook/leaflet-geojson-stream/output.geojson:1
(function (exports, require, module, __filename, __dirname) { "type":"FeatureC
^
SyntaxError: Unexpected token :
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/macbook/leaflet-geojson-stream/example/server.js:15:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
geojson文件看起来像。
{
"type": "FeatureCollection",
"features": [{
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-73.8283219965448, 40.8446061654002],
[-73.828397789942, 40.844583182304],
[-73.8285477331865, 40.8448132168025],
[-73.8284744943625, 40.8448401137412],
[-73.8283219965448, 40.8446061654002]
]
]
]
},
"type": "Feature",
, {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[-73.832361912256, 40.8488019205992],
[-73.832369554769, 40.8487286684528],
[-73.8327312374341, 40.8487518102579],
[-73.8327304815978, 40.8487590590352],
[-73.8327235953166, 40.8488250624279],
[-73.832361912256, 40.8488019205992]
]
]
]
},
"type": "Feature"
}
....
....
}
如何加载geojson文件?
答案 0 :(得分:1)
您目前正在将整个JSON文件加载到内存中,并要求&#39;它
相反,您希望流式传输文件,因为它很大,因此请使用fs.createReadStream函数:
var fs = require('fs');
app.get('/points.geojson', function(req, res) {
res.setHeader('Content-Type', 'application/json');
fs.createReadStream(__dirname + '/output.geojson').pipe(res);
});
还要确保 /output.geojson 的内容实际上是有效的JSON。您可以使用JSONLint进行检查 - 该文件应与&#39; {&#39;或者&#39; [&#39;并且里面没有Javascript函数。