node.js入门

node.js在ubuntu中的安装过程在前面一篇随笔里介绍了。

安装好node.js后,在任意路径新建文件helloworld.js,输入如下内容:

console.log("Hello world!")

然后在该路径下启动Terminal(Windows中就是命令行Command Line),或者先启动Terminal再使用cd命令切换到该路径也行(Windows同理),然后输入命令

node helloworld.js

回车,窗口中会输出“Hello world!”字样。

以上就是node的最简单的一个hello world程序。node.js作为服务器编程技术,另一个基本的hello world程序就是在网页上输出Hello world.

将helloworld.js的内容改成如下内容:

var http =require("http");//获取http对象

//利用http对象的createServer函数创建一个server对象,参数是一个无参函数,函数利用response对象向浏览器写入头信息和文本 var server = http.createServer(
function(request, response) { response.writeHead(200, {"Content-Type":"text/plain"}); response.write("Hello World"); response.end(); });

//server对象监听8888端口
server.listen(
8888);

然后再执行node helloworld.js,然后在浏览器中访问http://localhost:8888/

浏览器中就会显示Hello world!

原文地址:https://www.cnblogs.com/dige1993/p/4641497.html