1.开始
源码下载:https://github.com/sayar/NodeMVA
在线视频:https://mva.microsoft.com/en-US/training-courses/using-node-js-with-visual-studio-code-13920
2.事件驱动编程语言Nodejs
阻塞与非阻塞(Blocking I/O and Non Blocking I/O)
Blocking I/O
var fs = require('fs'); var contents = fs.readFileSync('package.json').toString(); console.log(contents);
Non Blocking I/O
var fs = require('fs'); fs.readFile('package.json', function (err, buf) { console.log(buf.toString()); });
Nodejs与C#相反,readFileSync表示阻塞线程,而readFile不阻塞线程异步执行方法,调用完成后执行callback方法。
注:在c#中同步方法一般为object.action,同步方法会阻塞线程等待耗时操作执行完成,异步方法为object.actionAsyc,异步方法经常有个异步事件可以注册待异步方法执行结束后调用。
3.Hello World
打开源码文件夹01_HelloWorld,包含两个文件app.js和package.json
app.js
console.log('Hello world'); //在控制台中输出Hello World , 令人熟悉的console类
package.json
{ "name": "_01_HelloWorld", "version": "0.0.0", "description": "Hello World", "main": "app.js", "author": { "name": "Rami Sayar", "email": "" } }
打开CMD执行命令node app可以看到执行结果Hello World。
$ cd 01_HelloWorld $ node app Hello World
4.FileIO
打开源码文件夹03_FILEIO
app.js
var fs = require('fs'); //阻塞I/O toString 用起来很顺手,比学C#简单多了 var contents = fs.readFileSync('package.json').toString(); console.log(contents); //非阻塞I/O fs.readFile('package.json', function (err, buf) { console.log(buf.toString()); });
5.Streams
打开源码文件夹06_Streams
app.js
var fs = require("fs"); // Read File fs.createReadStream("package.json") // Write File .pipe(fs.createWriteStream("out-package.json"));
6.HelloWorldHttp
打开源码文件夹02_HelloWorldHttp
app.js
var http = require('http'); //处理http请求,返回200ok hello world var server = http.createServer(function (request, response) { response.writeHead(200, { "Content-Type": "text/plain" }); response.end("Hello World "); }); //侦听7000端口 server.listen(7000);
7.HelloWorldTCP
打开源码文件夹05_HelloWorldTCP
server.js
var net = require('net'); // The handler argument is automatically set as a listener for the 'connection' event var server = net.createServer(function (socket) { console.log("Connection from " + socket.remoteAddress); socket.end("Hello World "); }); server.listen(7000, "127.0.0.1");
client.js
var net = require('net'); var client = new net.Socket(); client.connect(7000, "127.0.0.1"); client.on('data', function (data) { console.log('Data: ' + data); client.destroy(); }); // Add a 'close' event handler for the client socket client.on('close', function () { console.log('Connection closed'); });
打开两个CMD窗口,这两个窗口将会互相通讯。
$ cd 05_HelloWorldTCP $ node server
$ cd 05_HelloWorldTCP $ node client
8.Requests
打开源码文件夹10_Requests
app.js
var request = require("request"); request("http://www.bing.com", function(error, response, body) { console.log(body); });