0

I'm using NodeJS to fetch the NPM registry with the code below.

import fetch from "node-fetch";

let url = "https://registry.npmjs.com/[package-name]";

let settings = { method: "Get" };

fetch(url, settings)
    .then(res => res.json())
    .then((json) => {
    console.log(json.versions)
    });

So, the response that I get in my result is:

{
  _id: '123456789',
  name: 'package-name',
  'dist-tags': { latest: '2.0.0' },
  versions: {
    '2.0.0': '...'
}
...
}

I am trying to read the 'versions' section, but the issue I have is that the version number 2.0.0 is encased in quotes and it might change but I want to find that value. How can I read it?

Thanks in advance, and let me know any other info I missed.

  • 1
    Teminology nit: JSON doesn't have "tags". It's just **J**ava**S**cript **O**bject **N**otation. Also note that `res.json()` does not _return_ JSON at all, it returns a proper, real, JS datastructure. It's called `.json()` because you're asking it _parse_ JOSN, so you really want `...then(res => res.json()).then(data => ...).catch(...)` to make it obvious to both yourself and future code readers that by the time you hit the next then, we are no longer dealing with JSON in any way, shape, or form. – Mike 'Pomax' Kamermans Jun 12 '22 at 23:23
  • (As for the actual question: if this really is the actual data after JSON parssing, then we can see that the version number is the only key in the `versions` sub-object, so [get all keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) and then do what what we do with arrays) – Mike 'Pomax' Kamermans Jun 12 '22 at 23:24

1 Answers1

1

You'll have to check if the versions has the key you want.

if(Object.keys(response.versions).includes('2.0.0')){
  // response.versions['2.0.0'] exists
}

Or you could iterate through Object.keys(response.versions) and handle each version entry as you wish.

Gavin
  • 2,214
  • 2
  • 18
  • 26