Use semver package to determine if version matches

609 Views Asked by At

Say I have this in the .npm cache:

lodash/
  1.2.4/
  1.3.3/
  2.11.2/

What I want to do is read the directories in the lodash folder and see if any of the versions are acceptable.

Say I am looking for this version:

"lodash":"^2.11.1"

or

"lodash":"~2.11.1"

How can I compared the versions in the cache with the desired version, to see if a version in the cache, satisfies it?

This is what I have right now:

'use strict';

import semver = require('semver');
import async = require('async');
import * as cp from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

export const cacheHas = function (getCacheLocation: string, dep: string, version: string, cb: any) {

  const dir = path.resolve(getCacheLocation + '/' + dep);

  fs.readdir(dir, function (err, items) {

    if (err) {
      return cb(err);
    }

    const matches = items.some(function (v) {
      return semver.eq(v, version);
    });

    return cb(null, matches);

  });

};

so I am simply using semver.eq()....so my question is, is there a better call to use other than semver.eq()?

1

There are 1 best solutions below

0
On BEST ANSWER

The semver package has a satisfies function that does exactly that:

semver.satisfies(v, version)

(where v is what you've got in your cache, and version is the range you want to test if v satisfies)