用Node写网络服务程序非常简单

用Node写网络服务程序非常简单,可以考虑用在接口测试的Mock服务构建上


Node是什么:

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

用Node写Http服务程序或TCP服务程序的例子:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

To run the server, put the code into a file example.js and execute it with thenode program from the command line:

% node example.js

Server running at http://127.0.0.1:1337/


Here is an example of a simple TCP server which listens on port 1337 and echoes whatever you send it:

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

server.listen(1337, '127.0.0.1');

你可能感兴趣的:(用Node写网络服务程序非常简单)