在 node.js 服务器上生成 URL [英] generate URL on node.js server
问题描述
我正在寻找一种专业技术来生成唯一的 URL 地址.我创建了一个 node.js 服务器,它应该向访问客户端提供这些 URL.如何提供网址?
I'm looking for a professional technique to generate unique URL addresses. I created a node.js server that should give out these URLs to accessing clients. How can I provide the URLs?
// user is connecting to www.privatebox.de
// server serves index.html with unique ID
// e.g. www.privatebox.de/8yfuzyzzm7
推荐答案
对于稳健的解决方案,我会考虑使用 node-uuid 来生成 UUID.
For a robust solution, I would consider using node-uuid to generate UUIDs.
使用 NPM 安装包:
Install the package with NPM:
npm install node-uuid
基于来自 GitHub 项目页面的示例代码:
Based on the sample code from the GitHub project page:
var uuid = require('node-uuid');
// Generate a v1 (time-based) id
var timeBasedID = uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
// Generate a v4 (random) id
var randomID = uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'
var url = 'www.privatebox.de/' + randomID; // or + timeBasedID
如果您正在寻找更短、更适合 url 的唯一 ID,那么 ShortId 可能对您来说是一个不错的选择,尽管发生碰撞的机会会更高.ShortId 将生成如下 ID:
If you're looking for a shorter, more url-friendly unique ID, then ShortId might be a decent option for you, although the chance of collisions will be higher. ShortId will generate ids like this:
ShortId.generate() -> 'PPBqWA9'
最后,我建议你看看这个SO question 用于在 javascript 中生成唯一 ID.
Finally, I suggest you look at this SO question for generating unique ids in javascript.
这篇关于在 node.js 服务器上生成 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!