一、
1.安装node
2.编写第一个node.js文件 !!!文件后缀名保存为js
use strict';
console.log('Hello, world.');
运行:在命令行内输入node first.js
会输出hello,world.
3.在命令行模式下,可以执行node进入Node交互环境,可以输入js代码并立刻执行,会把每一行js代码的结果自动打印出来,但是运行js文件不会;
[bogon:~huizi $node
>100 + 200 +300
600
4.使用严格模式:js文件开头写上'use strict';
可以通过给nodejs传递参数,让node直接为所有js文件开启严格模式:node --use_strict calc.js
二、
1.创建第一个应用(一个可以工作的http服务)
引入require模块:使用require指令载入http模块,实例化的HTTP赋值给变量http
var http = require("http");
创建服务器:http.createServer()方法创建服务器,listen方法绑定端口,函数通过request,response参数来接收和响应数据。
'use strict';
var http = require("http");
http.createServer(function(request, response) {
//发生http头部
//http状态值200 :ok
//内容类型:text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
//发送响应数据
response.end('hello world\n');
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
打开浏览器输入http://127.0.0.1:8080/ 则可以看到显示hello world
2.使用npm命令安装模块:$ npm install <Module Name>
eg:安装Node.js web框架模块express:
$ npm install express //局部安装
$ npm install express -g //全局安装
安装好后通过require('express')引入代码:
var express = require('express');
npm cache clear 清空NPM本地缓存命令
其他详细介绍:http://www.runoob.com/nodejs/nodejs-npm.html
3.REPL(交互式解释器):http://www.runoob.com/nodejs/nodejs-repl.html
4.Node.js回调函数---Node.js异步编程的直接体现就是回调。
回调函数一般作为函数的最后一个参数出现:
function foo1(name,age,callback) {}
function foo2(value,callback1,callback2) {}
eg: //阻塞代码
var fs = require('fs');
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("程序执行结束");
输出结果:网址:www.runoob.com
程序执行结束
//非阻塞代码
fs.readFile('input.txt', function(err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("程序结束");
输出结果:程序结束