【学习笔记】nodejs之hello world~

来源:互联网 发布:mac怎么查找文件路径 编辑:程序博客网 时间:2024/06/05 17:10

上一节说过在REPL中运行console.log(‘hello world’);这条命令,我们可以可以和python的交互式命令一样很快输出结果,但是这离模块还有点差距,这一节我们创建一个简单的模块module,话不多说,show me code~

// require http modulevar http = require('http');//create servervar server = http.createServer();//bind function to request eventserver.on('request', function(req, res) {//write the headres.writeHead(200, {'content-type': 'text/plain'});//print string to the browserres.write('Hello World!');//response endedres.end();});//define the listening port with 8080var port = 8080;server.listen(port);//use the server once, there is some difference with server.onserver.once('listening', function() {console.log('Hello World server listening on port %d', port);});

上面的代码每行都加了注释,问题不会太大,运行模块之前需要做一些准备工作,检查一下我们的服务器安全组有没有开放8080端口,如果没有请添加自定义TCP端口。
我自己在操作的时候碰到过一个小问题,由于服务器连接的问题导致vim卡住,退出来之后使用恢复之后再进去还是提示要不要恢复。解决办法是,恢复了之后果断使用

rm -f <yourfile.swp> //删除swp恢复文件

后面就不会再提示了。
接下来开始运行模块,运行模块不是在交互式命令下,我开始在交互式命令下运行报错SyntaxError: Unexpected identifier,终端下直接运行以下命令,

node <yourmodule>.js hello world server listening on port 8080  //这句就是server.once的会话

打开浏览器,输入公网ip:8080就会出现hello world!

参考文献
instant nodejs starter.

原创粉丝点击