Search code examples
node.jsgeojsonjsdomdomparsergpx

NodeJS - Converting GPX to Geojson return empty array


I have a form where the user upload a GPX file and is then converted into Geojson, I use mapbox/togeojson module to achieve it and I have this code :

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)
    })

When I log the result of converted, I get : { type: 'FeatureCollection', features: [] }, which looks like Geojson structure but is not filled with the corresponding datas (I have checked on an online convertor that my GPX datas are good) I also tried using JSDOM as this tutorial suggests but with no results, I guess there is some data manipulation that is wrong on my code but I have no clue where.


Solution

  • Found the answer ! I didn't need the read the file, I just had to get the path of the uploaded file and then pass it to the new DOMParser() function to finally be converted in GeoJson (And didn't need JSDOM at all)

    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)
            })