You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If a number is supplied to ms, a string with a unit is returned
If a string that contains the number is supplied, it returns it as a number (e.g.: it returns 100 for '100')
If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
TypeScript support
As of v3.0, this package includes TypeScript definitions.
For added safety, we're using Template Literal Types (added in TypeScript 4.1). This ensures that you don't accidentally pass ms values that it can't process.
This won't require you to do anything special in most situations, but you can also import the StringValue type from ms if you need to use it.
importms,{StringValue}from'ms';// Using the exported type.functionexample(value: StringValue){ms(value);}// This function will only accept a string compatible with `ms`.example('1 h');
In this example, we use a Type Assertion to coerce a string.
importms,{StringValue}from'ms';// Type assertion with the exported type.functionexample(value: string){try{// A string could be "wider" than the values accepted by `ms`, so we assert// that our `value` is a `StringValue`.//// It's important to note that this can be dangerous (see below).ms(valueasStringValue);}catch(error: Error){// Handle any errors from invalid values.console.error(error);}}// This function will accept any string, which may result in a bug.example('any value');
You may also create a custom Template Literal Type.
importmsfrom'ms';typeOnlyDaysAndWeeks= `${number} ${'days'|'weeks'}`;// Using a custom Template Literal Type.functionexample(value: OnlyDaysAndWeeks){// The type of `value` is narrower than the values `ms` accepts, which is// safe to use without coercion.ms(value);}// This function will accept "# days" or "# weeks" only.example('5.2 days');
Advanced Usage
As of v3.0, you can import parse and format separately.
// Next.js (pages/api/edge.js) (npm i next@canary)// Other frameworks (api/edge.js) (npm i -g vercel@canary)importmsfrom'ms';conststart=Date.now();exportdefault(req)=>{returnnewResponse(`Alive since ${ms(Date.now()-start)}`);};exportconstconfig={runtime: 'experimental-edge',};
Fork this repository to your own GitHub account and then clone it to your local device
Link the package to the global module directory: npm link
Within the module you want to test your local development instance of ms, just link it to the dependencies: npm link ms. Instead of the default one from npm, Node.js will now use your clone of ms!