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;
}
데이터베이스 쿼리 콜백을 사용하여 변수 값을 설정하려면 어떻게 해야 합니까?내가 어떻게 할 수 있을까?
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'
** 업데이트 7.x
또, 상기의 사용법도 폐지되었습니다.따라서 이 패키지를 다음과 같이 사용합니다.
const {
v1: uuidv1,
v4: uuidv4,
} = require('uuid');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
방법은 네이티브32 문자 스트링을 입니다.crypto
★★★★
const crypto = require("crypto");
const id = crypto.randomBytes(16).toString("hex");
console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e
Node 14.17.0 이후 삽입 암호 모듈을 사용하여 UUID(UUIDv4 Flavored)를 생성할 수 있게 되었습니다.
const { randomUUID } = require('crypto'); // Added in: node v14.17.0
console.log(randomUUID());
// '89rct5ac2-8493-49b0-95d8-de843d90e6ca'
자세한 것은, https://nodejs.org/api/crypto.html#crypto_crypto_randomuuid_options 를 참조해 주세요.
★★★★★★crypto.randomUUID
uuid를 사용하다의존성을 추가할 필요가 없습니다.
심플한 시간 기반, 의존 관계 없음:
(new Date()).getTime().toString(36)
또는
Date.now().toString(36)
★★★★★jzlatihl
+ 난수 (@Yaroslav Gaponov의 답변 덕분에)
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
" "jzlavejjperpituute
edit: shortid는 더 이상 사용되지 않습니다.유지보수는 대신 나노이드를 사용할 것을 권장합니다.
또 다른 접근법은 npm의 shortid 패키지를 사용하는 것입니다.
매우 사용하기 쉽습니다.
var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF
에는 다음과 같은 매력적인 기능이 있습니다.
ShortId는 놀라울 정도로 짧은 비시퀀셜 URL 친화 고유 ID를 만듭니다.URL 단축자, MongoDB 및 Redis ID 및 기타 사용자에게 표시되는 ID에 적합합니다.
- 디폴트로는 7~14개의 URL 친화 문자: A~Z, a~z, 0~9, _-
- 비순차적이어서 예측할 수 없습니다.
- 중복되지 않고 하루에 수백만 개의 ID를 생성할 수 있습니다.
- ID를 반복하지 않고 앱을 몇 번이라도 재시작할 수 있습니다.
node.js를 사용한 지 꽤 되었지만 도움이 될 것 같습니다.
첫 번째로 노드에서는 1개의 스레드만 존재하며 콜백을 사용해야 합니다.는 어떻게 '신의코코코 what???? what what what'인가요?base.getID
는 큐잉됩니다.while
은 계속 루프로서 없이 됩니다.loop은 비지 루프입니다.
다음과 같이 콜백을 통해 문제를 해결할 수 있습니다.
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년 동안 노드/J를 코드화하지 않았고 테스트도 하지 않았습니다.그러나 기본적인 아이디어는 유효합니다.비지 루프를 사용하지 말고 콜백을 사용하는 것입니다.노드의 비동기 패키지를 확인할 수 있습니다.
node-uuid
권장되지 않으므로 를 사용하십시오.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'
모듈을 추가하지 않고 더욱 간단함
Math.random().toString(26).slice(2)
UUID를 설치하다
npm install --save uuid
uuid가 갱신되고 이전 Import가 실행됩니다.
const uuid = require('uuid/v4');
이 Import를 사용해야 합니다.
const {v4: uuid} = require('uuid');
이런 기능으로 사용할 수 있습니다.
const createdPlace = {
id: uuid(),
title,
description,
location: coordinates,
address,
creator
};
노드 v15.6.0+를 사용하는 경우crypto.randomUUID([options])
완전한 문서는 이쪽입니다.
내 5센트:
const crypto = require('crypto');
const generateUuid = () => {
return [4, 2, 2, 2, 6] // or 8-4-4-4-12 in hex
.map(group => crypto.randomBytes(group).toString('hex'))
.join('-');
};
포노의 끈은 아쉽게도 하이픈이 없어서 UUID 규격에 맞지 않아 많은 분들이 찾아오셨다고 생각합니다.
> generateUuid();
'143c8862-c212-ccf1-e74e-7c9afa78d871'
> generateUuid();
'4d02d4d6-4c0d-ea6b-849a-208b60bfb62e'
암호에 강한 UUID를 필요로 하는 사용자도 있습니다.
https://www.npmjs.com/package/generate-safe-id
npm install generate-safe-id
UUID를 사용할 수 없습니다.
랜덤 UUID(UUIDv4)에 엔트로피가 부족하여 전체적으로 고유합니다(아이언, 어?).랜덤 UUID의 엔트로피는 122비트밖에 없습니다.이는 2^61 ID 후에만 중복이 발생함을 나타냅니다.또한 일부 UUIDv4 구현에서는 암호학적으로 강력한 난수 생성기를 사용하지 않습니다.
이 라이브러리는 Node.js 암호화 RNG를 사용하여 240비트 ID를 생성합니다.이는 2^120 ID를 생성한 후 첫 번째 중복이 발생함을 나타냅니다.인류의 현재 에너지 생산량에 기초하면 이 임계값은 가까운 미래에는 넘을 수 없습니다.
var generateSafeId = require('generate-safe-id');
var id = generateSafeId();
// id == "zVPkWyvgRW-7pSk0iRzEhdnPcnWfMRi-ZcaPxrHA"
나는 이것을 사용하고 싶다.
class GUID {
Generate() {
const hex = "0123456789ABCDEF";
const model = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx";
var str = "";
for (var i = 0; i < model.length; i++) {
var rnd = Math.floor(Math.random() * hex.length);
str += model[i] == "x" ? hex[rnd] : model[i] ;
}
return str.toLowerCase();
}
}
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
console.log(new GUID().Generate());
아래를 사용하고 있으며, 서드파티 의존관계 없이 정상적으로 동작하고 있습니다.
const {
randomBytes
} = require('crypto');
const uid = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();
나노이드는 당신이 원하는 것과 정확히 같은 것을 성취합니다.
사용 예:
const { nanoid } = require("nanoid")
console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"
여기의 솔루션은 오래되어 현재는 권장되지 않습니다.https://github.com/uuidjs/uuid#deep-requires-now-deprecated
사용방법:
npm install uuid
//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);
npm에 https://www.npmjs.com/package/uniqid 사용
npm i uniqid
항상 현재 시간, 프로세스 및 시스템 이름을 기준으로 고유한 ID를 생성합니다.
- 현재 시간에서는 ID가 항상 단일 프로세스에서 고유합니다.
- 프로세스 ID를 사용하면 여러 프로세스에서 동시에 호출된 경우에도 ID는 고유합니다.
- MAC 주소에서는, 복수의 머신과 프로세스로부터 동시에 호출되어도, ID는 일의입니다.
특징:-
- 매우 빠르다
- 동시에 호출된 경우에도 여러 프로세스 및 시스템에서 고유한 ID를 생성합니다.
- 8바이트 및 12바이트의 짧은 버전으로 고유성이 떨어집니다.
YaroslavGaponov의 답변에서 확장하면, 가장 간단한 구현은 단지Math.random()
.
Math.random()
수학적으로, 실제 공간 [0, 1]에서 분수가 같을 확률은 이론적으로 0입니다. 확률적으로 node.js의 기본 길이 16개의 소수점에 대해 거의 0에 가깝습니다.또, 이 실장에서는 연산이 실행되지 않기 때문에, 산술의 오버플로우도 저감 할 수 있습니다.또한 10진수가 문자열보다 메모리를 적게 차지하기 때문에 문자열에 비해 메모리 효율이 높습니다.
저는 이것을 "Fractional-Unique-ID"라고 부릅니다.
1,000 1,000,000을 했습니다.Math.random()
중복된 숫자를 찾을 수 없습니다(최소한 기본 소수점 16의 경우).아래 코드를 참조하십시오(있는 경우 피드백을 제공하십시오).
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
패키지 urid를 사용할 수 .npm install urid
import urid from 'urid';
urid(); // qRpky22nKJ4vkbFZ
자세한 내용은 https://www.npmjs.com/package/urid를 참조하십시오.
// Set the size
urid(8); //ZDJLC0Zq
// Use the character set
urid('num'); // 4629118294212196
urid('alpha'); // ebukmhyiagonmmbm
urid('alphanum'); // nh9glmi1ra83979b
// Use size with character set
urid(12, 'alpha'); // wwfkvpkevhbg
// use custom character set
urid(6, '0123456789ABCDEF'); // EC58F3
urid('0123456789ABCDEF'); // 6C11044E128FB44B
// some more samples
urid() // t8BUFCUipSEU4Ink
urid(24) // lHlr1pIzAUAOyn1soU8atLzJ
urid(8, 'num') // 12509986
urid(8, 'alpha') // ysapjylo
urid(8, 'alphanum') // jxecf9ad
// example of all character sets
urid('num') // 5722278852141945
urid('alpha') // fzhjrnrkyxralgpl
urid('alphanum') // l5o4kfnrhr2cj39w
urid('Alpha') // iLFVgxzzUFqxzZmr
urid('ALPHA') // ALGFUIJMZJILJCCI
urid('ALPHANUM') // 8KZYKY6RJWZ89OWH
urid('hex') // 330f726055e92c51
urid('HEX') // B3679A52C69723B1
// custom character set
urid('ABCD-') // ACA-B-DBADCD-DCA
암호화로 강력한 의사 난수 데이터를 생성합니다.size 인수는 생성할 바이트 수를 나타내는 숫자입니다.
// Asynchronous
const {
randomBytes,
} = require('crypto');
randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: unique random ID ${buf.toString('hex')}`);
});
현재 솔루션의 벤치마크 중 하나는 나노이드 벤치마크입니다.
import { v4 as uuid4 } from 'uuid'
import benchmark from 'benchmark'
import shortid from 'shortid'
let suite = new benchmark.Suite()
suite
.add('crypto.randomUUID', () => {
crypto.randomUUID()
})
.add('nanoid', () => {
nanoid()
})
.add('uuid v4', () => {
uuid4()
})
.add("math.random", () => {
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
})
.add('crypto.randomBytes', () => {
crypto.randomBytes(32).toString('hex')
})
.add('shortid', () => {
shortid()
})
.on('cycle', event => {
let name = event.target.name
let hz = formatNumber(event.target.hz.toFixed(0)).padStart(10)
process.stdout.write(`${name}${pico.bold(hz)}${pico.dim(' ops/sec')}\n`)
})
.run()
그 결과는
node ./test/benchmark.js
crypto.randomUUID 13,281,440 ops/sec
nanoid 3,278,757 ops/sec
uuid v4 1,117,140 ops/sec
math.random 1,206,105 ops/sec
crypto.randomBytes 280,199 ops/sec
shortid 30,728 ops/sec
테스트 환경:
- 2.6GHz 6코어 인텔 Core i7 MacOS
- 노드 v16.17.0
let count = 0;
let previous = 0;
const generateUniqueId = () => {
const time = new Date().getTime()
count = time > previous ? 0 : (++count)
const uid = time + count
previous = uid
return uid
}
언급URL : https://stackoverflow.com/questions/23327010/how-to-generate-unique-id-with-node-js
'programing' 카테고리의 다른 글
SQL 예약어를 테이블 이름으로 사용하는 방법 (0) | 2022.09.21 |
---|---|
PHP에서 숫자를 월 이름으로 변환 (0) | 2022.09.21 |
값을 반환하지 않고 비포이드 함수의 끝에서 흘러내리면 컴파일러 오류가 발생하지 않는 이유는 무엇입니까? (0) | 2022.08.17 |
Python C API를 사용하여 생성기/반복기를 만드는 방법은 무엇입니까? (0) | 2022.08.17 |
에러노 스레드는 안전합니까? (0) | 2022.08.17 |