NodeJS - 将 GPX 转换为 Geojson return 空数组

NodeJS - Converting GPX to Geojson return empty array

我有一个表单,用户可以在其中上传 GPX 文件,然后将其转换为 Geojson,我使用 mapbox/togeojson 模块来实现它,我有以下代码:

const togeojson = require ('togeojson')
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const fs = require ('fs');
const DOMParser = require('xmldom').DOMParser;
const multer = require('multer');
const upload = multer({ dest: 'uploads/' })
module.exports = (express, Courses) => {

var courses_router = express.Router()

courses_router.route('/')
    .post(upload.single('gpxFile'),(req, res, next) => {
        let file = req.file
        if (file) {
            console.log("Uploaded : " + file.originalname + " to " + file.path)
            fs.readFile(file.path, (err, data) => {
                // let gpxJSDOM = new JSDOM(data)
                let gpx = new DOMParser().parseFromString(file.path, 'text/xml');
                let converted = togeojson.gpx(gpx)

            })
        }

        // var path = utils.ModifyString(req.body.title)
        // return false;
        // course_container.CreateCourses(Courses, req, res, path)
    })

当我记录 converted 的结果时,我得到:{ type: 'FeatureCollection', features: [] },它看起来像 Geojson 结构但没有填充相应的数据(我检查了 online convertor我的 GPX 数据很好) 我也尝试按照 tutorial 的建议使用 JSDOM,但没有结果,我想我的代码中有一些数据操作是错误的,但我不知道在哪里。

找到答案了!我不需要读取文件,我只需要获取上传文件的路径,然后将其传递给 new DOMParser() 函数,最终在 GeoJson 中进行转换(并且根本不需要 JSDOM)

const course_container = require('./../../containers/CourseContainer');
const utils = require('./../../../utils/functions')
const togeojson = require ('togeojson')
const fs = require ('fs');
const DOMParser = require('xmldom').DOMParser;
const multer = require('multer');
const path = require('path');
const upload = multer({ dest: 'uploads/' })
module.exports = (express, Courses) => {

    var courses_router = express.Router()

    courses_router.route('/')
        .post(upload.single('gpxFile'),(req, res, next) => {
            var file = req.file
            if (file) {
                var absolutePath = path.resolve(file.path);
                var gpx = new DOMParser().parseFromString(fs.readFileSync(absolutePath, 'utf8'));
                var geoJson = togeojson.gpx(gpx)
            }

            var course_path = utils.ModifyString(req.body.title)
            course_container.CreateCourses(Courses, req, res, course_path, geoJson)
        })