Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use npm package to validate a package name

Tags:

node.js

npm

Is there a way to use the npm package to validate a package name?

const npm = require('npm');

const isValid = npm.validatePackageName('foobar'); // true
const isValid = npm.validatePackageName('-4! *'); // false

I see a userland package that does this, but surely the npm package itself can do this? Is there a public utility exported from that package?

like image 682
Alexander Mills Avatar asked Apr 26 '18 19:04

Alexander Mills


2 Answers

Valid Names

var validate = require("validate-npm-package-name")

validate("some-package")
validate("example.com")
validate("under_score")
validate("123numeric")
validate("excited!")
validate("@npm/thingy")
validate("@jane/foo.js")

All of the above names are valid, so you'll get this object back:

{
  validForNewPackages: true,
  validForOldPackages: true
}

Invalid Names

validate(" leading-space:and:weirdchars")

That was never a valid package name, so you get this:

{
  validForNewPackages: false,
  validForOldPackages: false,
  errors: [
    'name cannot contain leading or trailing spaces',
    'name can only contain URL-friendly characters'
  ]
}

source : https://github.com/npm/validate-npm-package-name

like image 182
Nikita Ivanov Avatar answered Sep 18 '22 08:09

Nikita Ivanov


Naming Rules:

Below is a list of rules that valid npm package name should conform to:

  • Package name length should be greater than zero.
  • All the characters in the package name must be lowercase i.e., no uppercase or mixed case names are allowed.
  • Package name can consist of hyphens.
  • Package name must not contain any non-url-safe characters (since name ends up being part of a URL).
  • Package name should not start with . or _.
  • Package name should not contain any leading or trailing spaces.
  • Package name should not contain any of the following characters: ~)('!*
  • Package name cannot be the same as a node.js/io.js core module nor a reserved/blacklisted name. For example, the following names are invalid:
    • http
    • stream
    • node_modules
    • favicon.ico
  • Package name length cannot exceed 214.

Your package name consist of *; that is where the problem arises.

like image 35
nikhil sugandh Avatar answered Sep 22 '22 08:09

nikhil sugandh