mrkeyoor.comAsk

npm package

ms review

Use ms 2.1.3 for single-unit duration configuration when you can validate the parsed result yourself.

npmCLI & Toolingupdated 22 Nov 2026
767.5Mdownloads / wk

A missing unit changes what your timeout means: ms('100') returns 100 milliseconds. The npm package ms parses a single duration such as '2h' into milliseconds and formats numeric milliseconds as an English label. In ms 2.1.3, nonempty strings enter the parser and finite numbers enter the formatter. Use it where a CLI option or configuration value becomes a duration, then validate the result before passing it on.

Verdict

Use ms 2.1.3 for single-unit duration configuration when you can validate the parsed result yourself. First decide whether your configuration permits missing units and which positive durations it accepts. Keep numeric milliseconds for storage; consider pretty-ms for display or humanize-duration for translated output.

Answers from our run

ms or pretty-ms: which should you use?

Pick pretty-ms when pretty-ms converts milliseconds into a human-readable string. Consider it when your input is already numeric milliseconds and your task is display. The supplied registry metadata for version 10.0.0 declares Node >=22. Use ms 2.1.3 for single-unit duration configuration when you can validate the parsed result yourself.

When should you not use ms?

People need to enter combined units such as '1h 30m'. The anchored parser accepts one number and one optional unit.

API stability4/5This documentation-based score assesses the explicit 2.1.3 input contract, not future API stability. One exported function handles parsing and formatting, with a long formatting option. Malformed nonempty strings return undefined while empty strings throw, adding a handling burden that prevents a perfect score.
Docs3/5The version-pinned README provides parsing examples, negative values and long-format output. The supplied implementation is needed to establish the 100-character cutoff, anchored single-unit grammar and distinct invalid-input paths. The score credits useful examples while accounting for those missing explanations.
Maintenance3/5The 2.1.3 release notes list repository naming, linting, formatting and CI changes. This middle score reflects a documented patch record with limited evidence for judging maintenance. The supplied material does not establish current response times, ongoing support or abandonment, and no such finding is implied.
Ecosystem3/5The tagged implementation provides a CommonJS export, and the pinned README describes Node.js and browser use. That supports a documented integration role. No supplied runtime tests establish browser bundling, other module loaders or TypeScript setup. This score assesses documented fit without assigning a high score to unknown compatibility or adoption.

Use it if

Your configuration accepts one duration, such as '15m' or '2.5 hours', and application code needs milliseconds.
A Node.js script needs a short label such as '2h' for numeric elapsed time, with rounding acceptable.
You can enforce your own rules for missing units, negative values and maximum duration.
You want one function for parsing and formatting, and can keep string input distinct from numeric milliseconds.

Skip it if

People need to enter combined units such as '1h 30m'. The anchored parser accepts one number and one optional unit.
Your application needs calendar-aware years or daylight-saving days. Here a day is 24 hours and a year is 365.25 days.
You need exact, multi-unit display that preserves the original duration. Formatting at second magnitudes and above selects one unit and rounds.
Your interface needs translated duration labels. The formatter supplies English names and has no locale selection.
You expect a complete timeout validator. Negative values and unitless numbers are valid parser inputs, so application rules belong in your code.

Setup reality

Install the specified release with npm install ms@2.1.3. Its version-tagged implementation exports a CommonJS function through module.exports, so the examples use require('ms') in a .cjs file. These are illustrations checked against the supplied documentation and implementation, not executed application tests. The supplied evidence contains the version-tagged implementation and npm registry metadata. It contains no archive extraction, archive-to-tag comparison, installation result, benchmark or dependency audit. Browser bundling, TypeScript integration and other module loaders have no supplied test results.

The input type changes the operation. ms('100') returns the number 100, while ms(100) returns the string '100ms'. Keep configuration input as text until you parse it, and keep the parsed milliseconds numeric until you format a label. A nonempty string that does not match the grammar returns undefined. An empty string throws an Error. Unsupported input types and non-finite numeric inputs also take the error path. Catching exceptions alone therefore misses invalid values such as 'tomorrow'.

Validate before use. The parser allows fractions and negatives, defaults a missing unit to milliseconds, and returns undefined for strings longer than 100 characters. Reject blank input, check the parsed result with Number.isFinite, and apply a positive-value rule and a ceiling chosen for your application. The sample validator uses 24 hours as its own policy, not a package limit. It trims surrounding whitespace because the parser does not generally accept it. The validator still accepts unitless positive input as milliseconds.

Formatting can discard precision: 90,000 milliseconds becomes '2m'. Preserve the original numeric value for storage. At second magnitudes and above, short and long formatting select one unit and round; below one second they append a millisecond label without that rounding step. The long option supplies English unit names. Months and time zones have no representation in the parser, and a parsed year is a fixed duration rather than a calendar calculation.

Ratings use a documentation-based scale: 1 means poor fit or serious documented obstacles, 3 means useful with material limits, and 5 requires strong evidence across the dimension. Intermediate scores reflect the stated tradeoffs. The maintenance score assesses the supplied release record's usefulness for this review, not current maintainer responsiveness. The ecosystem score assesses documented integration fit, not adoption. None of these scores measures runtime compatibility.

Patterns

Parse one unit into milliseconds parse-duration

const ms = require('ms');

ms('2h');       // 7200000
ms('2.5 hrs');  // 9000000
ms('1 week');   // 604800000

Use require in a .cjs file after installing ms@2.1.3. All patterns are illustrations checked against the supplied source and were not executed. Each snippet repeats the import so it stands alone.

Keep strings and numbers distinct distinguish-input-types

const ms = require('ms');

ms('100'); // 100
ms(100);   // '100ms'

Unitless strings default to milliseconds. Passing a parsed number back into ms formats it into a string.

Check undefined as well as exceptions handle-invalid-text

const ms = require('ms');

ms('tomorrow'); // undefined
ms('1h 30m');   // undefined

try {
  ms('');
} catch (error) {
  console.error(error.message);
}

The anchored grammar rejects combined units. Empty strings throw before parsing, so a try/catch alone does not detect every invalid duration.

Apply an explicit timeout policy validate-config

const ms = require('ms');

function parseTimeout(raw) {
  if (typeof raw !== 'string') throw new TypeError('Use duration text');
  const text = raw.trim();
  if (!text) throw new Error('Timeout is required');
  const value = ms(text);
  const ceiling = 24 * 60 * 60 * 1000;
  if (!Number.isFinite(value) || value <= 0 || value > ceiling) {
    throw new RangeError('Use a positive duration up to 24 hours');
  }
  return value;
}

const timeoutMs = parseTimeout('30s'); // 30000

The 24-hour ceiling and trimming are application choices. This accepts unitless positive input as milliseconds. Add a separate unit requirement if your configuration contract needs one. The example has not been executed.

Decide whether negative values make sense handle-negative-duration

const ms = require('ms');

ms('-1h');    // -3600000
ms('-0.5s');  // -500
ms(-60000);  // '-1m'

Negative parsing and formatting are supported. Reject negatives when your application requires a positive interval.

Account for the parser's length limit respect-input-bound

const ms = require('ms');

const input = '1'.repeat(101);
ms(input); // undefined

The parser returns undefined when string length exceeds 100 characters. Shorter input still needs validation against your application's duration policy.

Format at the display boundary format-short-label

const ms = require('ms');

const elapsedMs = 90000;
const label = ms(elapsedMs); // '2m'
const parsedLabel = ms(label); // 120000

At second magnitudes and above, short formatting selects a unit by magnitude and rounds with Math.round. Preserve elapsedMs because parsing this label cannot recover the original value.

Spell out the chosen English unit format-long-label

const ms = require('ms');

ms(60000, { long: true });  // '1 minute'
ms(90000, { long: true });  // '2 minutes'
ms(500, { long: true });    // '500 ms'

The long option changes numeric formatting. At second magnitudes and above, it selects one unit and rounds. Below one second it appends ' ms'. The implementation supplies English names and no locale option.

Treat days and years as fixed durations use-fixed-duration

const ms = require('ms');

ms('1d'); // 86400000
ms('1y'); // 31557600000
ms('1mo'); // undefined

A year multiplies a fixed day by 365.25. The accepted units exclude months, and the function does not calculate a calendar anniversary.

Trim configuration text deliberately normalize-whitespace

const ms = require('ms');

const raw = ' 2h ';
ms(raw);        // undefined
ms(raw.trim()); // 7200000
ms('2 HRS');    // 7200000

The grammar permits literal spaces between number and unit and ignores unit case. It does not generally allow surrounding whitespace. Trimming is an application choice.

Alternatives

PackageRegistryPick it when
pretty-msnpmpretty-ms converts milliseconds into a human-readable string. Consider it when your input is already numeric milliseconds and your task is display. The supplied registry metadata for version 10.0.0 declares Node >=22.
humanize-durationnpmhumanize-duration converts millisecond durations to English and many other languages. Consider it when translated duration output matters. This comparison uses the supplied description for version 3.35.1, not an integration test.

More cli & tooling guides

How this guide is made: grounded in the library's documentation, release notes, changelog, and issue history, on a fixed rubric — not a hands-on install of every release. The 50 most-downloaded entries are additionally install-verified in clean containers. Corrections: contact the desk.