Programming

node.js로 고유 ID를 생성하는 방법

procodes 2020. 7. 1. 22:17
반응형

node.js로 고유 ID를 생성하는 방법


function generate(count) {
    var founded = false,
        _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
        str = '';
    while(!founded) {
        for(var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        base.getID(string, function(err, res) {
            if(!res.length) {
                founded = true; // How to do it?
            }
        });
    }
    return str;
}

데이터베이스 쿼리 콜백으로 변수 값을 설정하는 방법은 무엇입니까? 어떻게 할 수 있습니까?


node.js를 사용한 지 얼마되지 않았지만 도움이 될 것 같습니다.

첫째, 노드에는 단일 스레드 만 있으며 콜백을 사용해야합니다. 코드에서 일어날 일은 base.getID쿼리가 실행을 위해 큐에 대기되지만 while루프는 소중하게 바쁜 루프로 계속 실행됩니다.

다음과 같이 콜백으로 문제를 해결할 수 있어야합니다.

function generate(count, k) {
    var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
    var str = '';

    for(var i = 0; i < count; i++) {
        str += _sym[parseInt(Math.random() * (_sym.length))];
    }
    base.getID(str, function(err, res) {
        if(!res.length) {
          k(str)                   // use the continuation
        } else generate(count, k)  // otherwise, recurse on generate
    });
}

그런 식으로 사용하십시오

generate(10, function(uniqueId){
  // have a uniqueId
})

나는 약 2 년 동안 노드 / JS를 코딩하지 않았으며 이것을 테스트하지는 않았지만 기본 아이디어는 사용하지 않아야합니다. 바쁜 루프를 사용하지 말고 콜백을 사용하십시오. 노드 비동기 패키지를 살펴볼 수 있습니다.


NPM uuid 패키지 설치 ( 출처 : https://github.com/kelektiv/node-uuid ) :

npm install uuid

코드에서 사용하십시오.

var uuid = require('uuid');

그런 다음 ID를 만드십시오 ...

// Generate a v1 (time-based) id
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'

// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

** 업데이트 3.1.0
위의 사용법은 이상 사용 되지 않으므로 다음같이이 패키지를 사용하십시오.

const uuidv1 = require('uuid/v1');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

const uuidv4 = require('uuid/v4');
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

노드에서 임의의 32 문자 문자열을 만드는 가장 빠른 방법은 기본 crypto모듈 을 사용하는 것입니다 .

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

또 다른 방법은 npm shortid 패키지를 사용하는 입니다.

사용하기 매우 쉽습니다 :

var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF

몇 가지 매력적인 기능이 있습니다.

ShortId는 놀라 울 정도로 짧은 비 순차 URL 친화적 인 고유 ID를 만듭니다. URL 단축기, MongoDB 및 Redis ID 및 기타 모든 id 사용자에게 적합합니다.

  • 기본적으로 7-14 개의 URL 친화적 문자 : AZ, az, 0-9, _-
  • 비 순차적이므로 예측할 수 없습니다.
  • Can generate any number of ids without duplicates, even millions per day.
  • Apps can be restarted any number of times without any chance of repeating an id.

node-uuid is deprecated so please use uuid

npm install uuid --save
// Generate a v1 UUID (time-based) 
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

// Generate a v4 UUID (random) 
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Npm link


More easy and without addition modules

Math.random().toString(26).slice(2)

If some one needs cryptographic-strong UUID, there is solution for that as well.

https://www.npmjs.com/package/generate-safe-id

npm install generate-safe-id

Why not UUIDs?

Random UUIDs (UUIDv4) do not have enough entropy to be universally unique (ironic, eh?). Random UUIDs have only 122 bits of entropy, which suggests that a duplicate will occur after only 2^61 IDs. Additionally, some UUIDv4 implementations do not use a cryptographically strong random number generator.

This library generates 240-bit IDs using the Node.js crypto RNG, suggesting the first duplicate will occur after generating 2^120 IDs. Based on the current energy production of the human race, this threshold will be impossible to cross for the foreseeable future.

var generateSafeId = require('generate-safe-id');

var id = generateSafeId();
// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"

Simple, time based, without dependencies:

(new Date()).getTime().toString(36)

Output: jzlatihl


plus random number (Thanks to @Yaroslav Gaponov's answer)

(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)

Output jzlavejjperpituute

참고URL : https://stackoverflow.com/questions/23327010/how-to-generate-unique-id-with-node-js

반응형