在 Node.js 中生成隨機短 ID


可以使用 NPM 的'shortId' 包來建立短非序列 URL 友好的唯一 ID。預設情況下,它從以下類別返回 7-14 個 URL 友好的字元:“A-Z、a-z、0-9、_、-” 。此包還支援叢集(自動)、自定義種子和自定義字母表。它可以在不重複的情況下生成任意數量的 ID。

語法

  • 設定 NPM 專案

npm init -y
  • 安裝'shortId' 依賴項

npm install express shortid
  • 匯入shortId:

const short = require('shortid');

示例 1

建立一個名為"shortId.js" 的檔案,並複製以下程式碼片段。建立檔案後,使用命令"node shortId.js" 來執行此程式碼,如下面的示例所示 −

// Generating Random Short Id in Node.js
// Importing the express & shortId module
const express = require('express');
const short = require('shortid');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;
app.get('/api' , (req , res)=>{
   // generating short random Id
   res.send(short());
})
// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

帶著GET 請求訪問以下端點:localhost:3000/api

UGjx0nys_

示例 2

我們來看另外一個例子。

// Generating Random Short Id in Node.js

// Importing the express & shortId module
const express = require('express');
const short = require('shortid');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;
app.get('/api' , (req , res)=>{
   // generating short random Id
   console.log("1. ", short());
   console.log("2. ", short());
   console.log("3. ", short());
   console.log("4. ", short());
   res.end();
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

帶著GET 請求訪問以下端點:localhost:3000/api

C:\home
ode>> node shortId.js Server listening on PORT 3000 1. Utw_TxFec 2. YHFJhDSMQ4 3. YxnJzSynVu 4. e5SpHUBCFf

更新於:2022-04-06

1K+ 瀏覽

開啟您的職業生涯

完成課程,獲取認證

立即開始
廣告