在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP