目录
好了, 上一篇文章已经讲了node环境安装,这里我们开始第一个经典程序 helloworld
入门之helloworld
console.log("hello world");
运行 node hello.js
[root@VM_0_9_centos ~]# node hello.js
hello world
就是这么简单,console.log是在控制台打印输出信息的函数。
进阶之helloworld http服务器
之前我们用php做web网站的时候,需要 Apache 或者 Nginx 的 HTTP 服务器,并配上 mod_php5 模块和 php-cgi,整个"接收 HTTP 请求并提供 Web 页面"的需求就不需要 PHP 来处理。
不过对 Node.js 来说,概念完全不一样了。使用 Node.js 时,我们不仅仅 在实现一个应用,同时还实现了整个 HTTP 服务器。事实上,我们的 Web 应用以及对应的 Web 服务器基本上是一样的。
在我们创建 Node.js 第一个 "Hello, World!" 应用前,让我们先了解下 Node.js 应用是由哪几部分组成的:
-
引入 required 模块:我们可以使用 require 指令来载入 Node.js 模块。
-
创建服务器:服务器可以监听客户端的请求,类似于 Apache 、Nginx 等 HTTP 服务器。
-
接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。
步骤一、引入 required 模块
我们使用 require 指令来载入 http 模块,并将实例化的 HTTP 赋值给变量 http,实例如下:
var http = require("http");
步骤二、创建服务器
接下来我们使用 http.createServer() 方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过 request, response 参数来接收和响应数据。
实例如下,在你项目的根目录下创建一个叫 server.js 的文件,并写入以下代码:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
// 发送响应数据 "Hello World"
response.end('Hello World\n');
}).listen(80);
console.log('Server running at http://127.0.0.1/');
以上代码我们完成了一个可以工作的 HTTP 服务器。
使用 node 命令执行以上的代码:
node server.js
Server running at http://127.0.0.1/
基本语法篇
变量声明
在 C/C++ 中,我们这么声明变量的:
void fun() {}
int a = 0;
char b =