node.js 学习笔记一:创建一个服务器

var http = require("http");

http.createServer(function(request, response){
	response.writeHead(200, {"Content-Type": "text/plain"});
	response.write("Hello,World");
	response.end();
}).listen(8888);

保存文件为server.js, 在命令行里运行代码node server.js

在浏览器地址栏输入 http://localhost:8888

ps:js最牛逼的地方是把整个函数当参数传递给我别的函数

所以你也可以这样写,但比较传统,不够文艺了,如下:

function onRequest(request, response){
	response.writeHead(200, {"Content-Type": "text/plain"});
	response.write("Hello,World,Node.js");
	response.end();
}

http.createServer(onRequest).listen(8888);

  

原文地址:https://www.cnblogs.com/bjdxy/p/2918230.html