32

I would like to parse xml data, retrieved from the server. Unfortunately HttpClient does not support xml, only json, therefore I installed the package xml2js:

npm install xml2js --save
npm install @types/xml2js --save-dev

Then I try to use it like this:

import {Parser} from 'xml2js';

Parser.parseString(xml_str, function (err, result) {
    console.dir(result);
});

I get these two errors if I run it:

WARNING in ./node_modules/xml2js/node_modules/sax/lib/sax.js
Module not found: Error: Can't resolve 'stream' in 'C:\projects\app\node_modules\xml2js\node_modules\sax\lib'

ERROR in ./node_modules/xml2js/lib/parser.js
Module not found: Error: Can't resolve 'timers' in 'C:\projects\app\node_modules\xml2js\lib'

I haven't found any solutions to this problem, maybe it is an Angular6 issue only. Is there any way, to parse xml in Angular6?

2 Answers 2

61

You’ll have to install those dependencies. It’s unfortunately not well documented.

npm install --save stream timers
3
  • Unfortunately, it only allows compiling. The npm timers package does not provide function setImmediate, so at the runtime an error (TypeError: setImmediate is not a function) is still thrown. Something about that is here: github.com/Leonidas-from-XIV/node-xml2js/issues/301 but it still does not suggest a solution. Commented Nov 16, 2018 at 15:31
  • btw. stream and timers last commit is over 5..7 years ago.
    – Domske
    Commented Sep 2, 2019 at 12:43
  • 1
    Thanks a lot. this solved my problem like charm! :) Commented Jun 17, 2020 at 13:29
29

For Angular to recognise xml2js, the following steps are required:

  1. Add the timers-browserify node module using "npm install timers-browserify"
  2. Add the stream-browserify node module using "npm install stream-browserify"
  3. Add the following path mapping in your tsconfig.json:
    "compilerOptions": {
      "paths": {
        "timers": [
          "node_modules/timers-browserify"
        ],
        "stream": [
          "node_modules/stream-browserify"
        ],
      }
    }
5
  • This resolved the issue I was having Module not found: Error: Can't resolve 'stream', thanks!
    – kue
    Commented Sep 6, 2020 at 14:03
  • Why did you only say install and not install --save? Everyone seems to do this can't figure out why, if the person doesn't do --save they will have to explicitly re-add it every time?
    – Dan Chase
    Commented Apr 14, 2023 at 17:03
  • This solution worked for me Thanks
    – PPr
    Commented Sep 21, 2023 at 6:16
  • Perfect, this worked!. (Angular 14). I'm gratefully.
    – FerMV
    Commented Oct 27, 2023 at 23:25
  • 2
    @DanChase Starting from npm version 5 and later, npm introduced the automatic saving of dependencies without the need for the --save flag. You don't need to type --save explicitly if you're using newer version of npm.
    – izogfif
    Commented Mar 27 at 20:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.