Giter Site home page Giter Site logo

uniqid's Introduction

uniqid logo

unqiid npm badge uniqid npm downloads badge

A Unique Hexatridecimal ID generator.

It will always create unique id's based on the current time, process and machine name.

// install with npm 
npm install uniqid

// install with yarn
yarn add uniqid

Usage

import uniqid from 'uniqid';

console.log(uniqid()); // -> 4n5pxq24kpiob12og9
console.log(uniqid(), uniqid()); // -> 4n5pxq24kriob12ogd, 4n5pxq24ksiob12ogl

Usage with Require

var uniqid = require('uniqid'); 

console.log(uniqid()); // -> 4n5pxq24kpiob12og9
console.log(uniqid(), uniqid()); // -> 4n5pxq24kriob12ogd, 4n5pxq24ksiob12ogl

Usage in Browser

Take advantage of content delivery networks for Prototyping/Mockups

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://unpkg.com/browse/[email protected]/UMD/uniqid.min.js"></script>
    <script>
        alert(`Here is an ID: ${uniqid()}`)
    </script>

    <title>Your App</title>
</head>

<body>

</body>

</html>

Features

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

How it works

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

API:

uniqid( prefix optional string , suffix optional string )

Generate 18 byte unique id's based on the time, process id and mac address. Works on multiple processes and machines.

uniqid() -> "4n5pxq24kpiob12og9"
uniqid('hello-') -> "hello-4n5pxq24kpiob12og9"
uniqid('hello-', '-goodbye') -> "hello-4n5pxq24kpiob12og9-goodbye"

// usage with suffix only
uniqid('', '-goodbye') -> "4n5pxq24kpiob12og9-goodbye"
uniqid(undefined, '-goodbye') -> "4n5pxq24kpiob12og9-goodbye"

uniqid.process( prefix optional string , suffix optional string )

Generate 12 byte unique id's based on the time and the process id. Works on multiple processes within a single machine but not on multiple machines.

uniqid.process() -> "24ieiob0te82"

uniqid.time( prefix optional string , suffix optional string )

Generate 8 byte unique id's based on the current time only. Recommended only on a single process on a single machine.

uniqid.time() -> "iob0ucoj"

Webpack, Browserify, Vite

Since browsers don't provide a Process ID and in most cases neither give a Mac Address using uniqid from Webpack, Browserify and Vite falls back to uniqid.time() for all the other methods too. The browser is the single process, single machine case anyway.

Debug

Debug messages are turned off by default as of v4.1.0. To turn on debug messages you'll need to set uniqid_debug to true before you require the module.

// enable debug messages
module.uniqid_debug = true;

// require the module
var uniqid = require('uniqid');

License

(The MIT License)

Copyright (c) 2014-2021 Halász Ádám [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

uniqid's People

Contributors

adamhalasz avatar blittle avatar braincrumbz avatar brammitch avatar clickwithclark avatar dnhb-nick avatar jameskyburz avatar joeldenning avatar jonathanstoye avatar karaggeorge avatar no1mick avatar nth-chile avatar pravi avatar s4uron avatar stevenvachon avatar vcastelain avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uniqid's Issues

"Missing initializer in const declaration" caused when building minified bundle.

Missing initializer in const declaration error when creating minified build

const networkInterface,length;

Solution:
Replace

if(typeof __webpack_require__ !== 'function'){
    var mac = '', networkInterfaces = require('os').networkInterfaces();
    for(interface_key in networkInterfaces){
        var networkInterface = networkInterfaces[interface_key];
        var length = networkInterface.length;
        for(var i = 0; i < length; i++){
            if(networkInterface[i].mac && networkInterface[i].mac != '00:00:00:00:00:00'){
                mac = networkInterface[i].mac; break;
            }
        }
    }
    address = mac ? parseInt(mac.replace(/\:|\D+/gi, '')).toString(36) : '' ;
}

const networkInterface -> var networkInterface
const length -> var length

Error when network address is not available

Hello, I'm using uniqid. If I turn my wifi off (no network connection), it exits with an error I can't handle.

$ gulp command

/Users/psyx/psyxgen/node_modules/uniqid/index.js:11
require('macaddress').one(function(error, macAddress){ if(error) throw error; address = macAddress; });
                                                                 ^
no interfaces found
$

Is there a workaround? Thanks.

Collision issue

This package is NOT safe for use on the front end. The method being used to generate a unique id is VERY prone to collisions. This caused all kinds of weird flake in our system that took a significant amount of time to track down.

I would recommend using https://github.com/ai/nanoid/ instead (both for the front-end and the back-end)

TypeError: Cannot read property 'mac' of undefined

If I add an Object.prototype function to my project, I get this error.

Example function to reproduce:

Object.prototype.pickProperties = function(keys) {
console.log("called!");
var clone = {};
for(var i = 0; i < keys.length; i++) {
var key = keys[i];
if(this.hasOwnProperty(key)) {
clone[key] = this[key];
}
}
return clone;
};

TypeError: Cannot read property 'mac' of undefined
at Object. (...\node_modules\uniqid\index.js:22:36)

I'm using the latest Version: [email protected]

Release npm for major fix

Hi,

Can you bump npm version witch include major fix in pull request #11, please ?

Fail when module is web bundled (browserify).

Thanks.

Doesn't run in react native

I guess the os package isn't supported in react native.

I see this error:

bundling failed: Error: Unable to resolve module `os` from `C:\dev\node_modules\uniqid\index.js`: Module `os` does not exist in the Haste module map

Safety when node clusters are used

Hi,

The uniqId is generated from Date.getTime() function, the uniquness is guaranteed when running only one node process, but what about running a node app on multiple clusters, probably, a collision may occure.

Thanks

Error when importing uniqID in vite project

When uniqID is imported into vite, the following error occurs:
require_os(...).networkInterfaces is not a function
After checking the code, it is because of this code:
if(typeof __webpack_require__ !== 'function'){ var mac = '', networkInterfaces = require('os').networkInterfaces(); loop: for(let interface_key in networkInterfaces){ const networkInterface = networkInterfaces[interface_key]; const length = networkInterface.length; for(var i = 0; i < length; i++){ if(networkInterface[i] !== undefined && networkInterface[i].mac && networkInterface[i].mac != '00:00:00:00:00:00'){ mac = networkInterface[i].mac; break loop; } } } address = mac ? parseInt(mac.replace(/\:|\D+/gi, '')).toString(36) : '' ; }

Because webpack_require does not exist in vite, the code that enters it will report an error

Released NPM package should include a transpiled cjs module copy

Most bundle tool (e.g. rollup & Webpack ) should assume the entry file specify by "main" field of the package.json is a CJS module without any es2015.

The current index.js file contains const keyword will cause issues to minifier (e.g. uglify) as they are supposed to work with transpiled code only.

Failed to minify the code from this file: node_modules/uniqid/index.js:18

I ran "npm audit fix" and it upgraded uniqid to 5.2.0 but when i attempt to run a build it breaks with:

Failed to minify the code from this file: node_modules/uniqid/index.js:18

I downgraded uniqid package to 5.0.3 and the error went away.

The error is so cryptic I couldn't even track down the line. The line 18 above is just a for in loop.

BTW... I am not using react-scripts and ejected long ago..

Create only number

Hi, I want to increment unique ID with only number. Can I do with this lib?
And I want to start with 20000 then if I created new entry for collection.

Thank you.

'process && process.pid' test doesn't work in strict mode

I'd suggest changing the following:
var pid = process && process.pid ? process.pid.toString(36) : '' ;
to:
var pid = typeof process !== 'undefined' && process.pid ? process.pid.toString(36) : '' ;

The 2nd version is more portable and safer. I pulled the uniqid module into an Angular 6 project and the code ended up running in strict mode, which caused a ReferenceError on 'process'.

Bug – Reserved word with browserify

This bug didn't exist in version 4.1.1. Now requiring the module with browserify (16.2.2) returns:

SyntaxError: unknown: interface is a reserved word in strict mode (475:14)
  473 |     var mac = '', interfaces = require('os').networkInterfaces();
  474 |     for(interface_key in interfaces){
> 475 |         const interface = interfaces[interface_key], length = interface.length;
      |               ^
  476 |         for(var i = 0; i < length; i++){
  477 |             if(interface[i].mac && interface[i].mac != '00:00:00:00:00:00'){
  478 |                 mac = interface[i].mac; break;

Characters length

Is there any way to set characters length. Because it's not fixed. But I really need it to be fixed length

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.