(转)NodeJS - 第一个应用程序Hello World
2024-10-07 22:13:03
安装NodeJs
在创建实际的“Hello,World!”应用之前,我们应该先安装NodeJS,安装NodeJS可以访问NodeJS官网,下载相应系统的NodeJS的安装包,进行安装。
程序组件
关于Hello World 这个应用主要包括三部分组成
导入所需的模块
-在程序中我们使用require指令来加载NodeJS模块创建服务器
-一个将监听类似于Apache HTTP Server的客户端请求的服务器。- 请求和响应
-在先前步骤中创建的服务器将读取由客户端(可以是浏览器或控制台)发出的HTTP请求并返回响应
创建NodeJS应用程序
第1步 - 导入所需模块
我们使用require指令加载http模块并将返回的HTTP实例存储到http变量中,如下所示
var http = require("http");
- 1
第2步 - 创建服务器
我们使用创建的http实例并调用http.createServer()方法创建服务器实例,然后使用与服务器实例关联的listen方法将其绑定到端口3000 。通过参数请求和响应传递一个函数。编写样本实现以始终返回“Hello World”。
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(3000);
// Console will print the message
console.log('Server running at http://127.0.0.1:3000/');
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
第3步现在执行main.js来启动服务器
$ node main.js
- 1
我们可以看到程序已经启动
这时我们打开浏览器输入http://127.0.0.1:3000/ 可以看到:
最新文章
- 【原创】kafka client源代码分析
- 【leetcode】Reverse Bits(middle)
- 纯css3绘制扇形
- ASP.NET 4.0 forms authentication issues with IE11
- servlet 配置
- 封装数据库mysql, mysqli
- 单源最短路径——Floyd算法
- Java中构造函数执行顺序的问题
- 杂乱无章之Oracle(一)
- You must supply a layout_width attribute的错误原因及解决办法
- DOM五大对象
- wcf中 生成x5.09证书的工具
- dpdk组态 千兆网卡 驱动 失败 原因分析及 解决方案
- 【转】HTTP响应报文与工作原理详解
- webapp万能选择器:iosselect
- C#之UDP通信
- 如何让写得html页面自动刷新
- MOOC Linux内核之旅小结【转】
- ActiveReports 大数据分析报告:贸易争端与中国企业数字化转型
- POJ3628:Bookshelf 2【01背包】
热门文章
- NX二次开发-UFUN查询对象的类型和子类型UF_OBJ_ask_type_and_subtype
- python virtual env 使用 jupyter ipython notebook,舒服了, 工作效率翻倍
- 使用Docker创建数据容器
- 自动化测试工具2-testcomplete
- python中面向对象
- python中字典排序
- 初识OpenCV-Python - 001
- 2018ICPC焦作 D-Keiichi Tsuchiya the Drift King /// 几何
- drools语法介绍
- 服务启动脚本start_boot.sh