Aug 28, 2012 - node.js    No Comments

Node.js Hello node-uuid

上次装node.js环境的时候装了一个node-uuid的module,这是一个简单快速生成一个全局唯一标示符的module。(uuid = Universally Unique IDentifier)

// 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'

可以看出v1();是生成一个时间戳uuid。 v4();是生成一个纯随机数uuid。

在 ~/node 目录下新建一个hello-uuid.js,代码如下:

var http = require('http');
var uuid = require('node-uuid');
http.createServer(function(req, res) {
	id1 = uuid.v1();
	id2 = uuid.v4();
	res.writeHead(200, {
		'Content-Type': 'text/plain;charset=UTF-8'
	});
	res.end('v1: ' + id1 + '\nv4: ' + id2);
}).listen(1216, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1216/');

在命令行里启动hello-uuid.js

$ node hello-uuid.js

在到浏览器里访问:http://127.0.0.1:1216/
可以看到每次刷新都会得到两串新的uuid

v1: 0da00e40-f062-11e1-aad1-95d3f9abc2ba
v4: eb844195-2052-4286-964b-765deed13ae6

Got anything to say? Go ahead and leave a comment!