(二)nodejs循序渐进-nodejs基本类型和循环条件语法篇(基础篇)

目录

入门之helloworld

进阶之helloworld  http服务器

步骤一、引入 required 模块

步骤二、创建服务器

基本语法篇 

变量声明

基础类型 

if else 

循环语句

for

for ... in

 while  do和do while

运算符 

加减乘除

==, ===, !=, !== 

typeof 

null,undefined,NaN


 

好了, 上一篇文章已经讲了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 应用是由哪几部分组成的:

  1. 引入 required 模块:我们可以使用 require 指令来载入 Node.js 模块。

  2. 创建服务器:服务器可以监听客户端的请求,类似于 Apache 、Nginx 等 HTTP 服务器。

  3. 接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送 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 = 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值