├── chapter09 ├── test │ └── test.txt ├── ch09.path_dirname.js ├── ch09.path_extname.js ├── ch09.path_join.js ├── ch09.path_resolve.js ├── ch09.url_resolve.js ├── ch09.querystring_parse.js ├── ch09.url_parse_format.js └── ch09.path_relative.js ├── Chapter11 ├── data │ ├── destFile.txt │ ├── read.txt │ ├── basic.txt │ ├── data.txt │ ├── readable.txt │ ├── srcDrain.txt │ ├── createReadStream.txt │ ├── destFinish.txt │ ├── srcFinish.txt │ ├── writable.txt │ ├── pause.txt │ ├── srcFile.txt │ ├── destUnFile.txt │ ├── srcUnFile.txt │ ├── srcDrain.mp3 │ └── fs_readFileSync.js ├── ch11.stream_readable_readableA.js ├── ch11.stream_readable_pipe.js ├── ch11.stream_writable_file.js ├── ch11.stream_readable_pipe_push.js ├── ch11.stream_readable_error.js ├── ch11.stream_readable_readableB.js ├── ch11.stream_readable_unpipe.js ├── ch11.stream_readable_read.js ├── ch11.stream_readable_basic.js └── ch11.stream_writable_drain.js ├── chapter08 ├── txt │ ├── fchmodSync.txt │ ├── watchFile.txt │ ├── chmod.txt │ ├── link.txt │ ├── read.txt │ ├── truncate.txt │ ├── fchmod.txt │ ├── ftruncate.txt │ ├── symlink.txt │ ├── chmodSync.txt │ ├── linkSync.txt │ ├── open.txt │ ├── readFile.txt │ ├── readSync.txt │ ├── realpath.txt │ ├── writeFile.txt │ ├── chown.txt │ ├── fchown.txt │ ├── readFileSync.txt │ ├── realpathSync.txt │ ├── symlinkSync.txt │ ├── chownSync.txt │ ├── fstat.txt │ ├── helloworld-asyn.txt │ ├── helloworld-syn.txt │ ├── openSync.txt │ ├── stat.txt │ ├── truncateSync.txt │ ├── writeFileSync.txt │ ├── statSync.txt │ ├── fstatSync.txt │ ├── ftruncateSync.txt │ ├── appendFile.txt │ ├── appendFileSync.txt │ ├── writeSync.txt │ └── write.txt ├── txtlink │ ├── symlink.txt │ └── symlinkSync.txt ├── ch08.fs_readdirSync.js ├── ch08.fs_statSync.js ├── ch08.fs_fstatSync.js ├── ch08.fs_realpathSync.js ├── ch08.fs_stat.js ├── ch08.fs_realpath.js ├── ch08.fs_readlinkSync.js ├── ch08.fs_readdir.js ├── ch08.fs_readFileSync.js ├── ch08.fs_fstat.js ├── ch08.fs_chownSync.js ├── ch08.fs_watchFile.js ├── ch08.fs_openSync.js ├── ch08.fs_fchownSync.js ├── ch08.fs_readFile.js ├── ch08.fs_open.js ├── ch08.fs_readlink.js ├── ch08.fs_renameSync.js ├── ch08.fs_writeFileSync.js ├── ch08.fs_truncateSync.js └── ch08.fs_ftruncateSync.js ├── chapter05 ├── stderr.txt ├── ch05.process-cwd.js ├── ch05.process-sysinfo-shell.js ├── ch05.process-sysinfo-nodeconfig.js ├── ch05.process-sysinfo-pid.js ├── ch05.process-sysinfo-cpu.js ├── ch05.process-sysinfo-node.js ├── ch05.process-chdir-win.js ├── ch05.process-sysinfo-process.js ├── ch05.process-chdir.js ├── ch05.process-stderr.js ├── ch05.process-stdout.js ├── ch05.process-kill.js ├── ch05.process-stdin.js ├── ch05.process-nextTick.js └── ch05.process-sysinfo.js ├── chapter01 ├── error.txt ├── ch01.hello-world.js ├── ch01.log-info.js ├── ch01.console-assert.js ├── ch01.obj-dir.js ├── ch01.format-data.js ├── ch01.format-logic.js ├── ch01.time-timeend.js ├── ch01.format-argument.js ├── ch01.format-json.js ├── ch01.stderr-file.js ├── ch01.error-warn.js ├── ch01.console-narcissus.js ├── ch01.format-string.js ├── ch01.console-write.js ├── ch01.console-trace.js ├── ch01.console-readline.js ├── ch01.console-fibonacci.js ├── ch01.console-tinyCLI.js ├── ch01.console-factorial.js ├── ch01.console-primeNum.js └── ch01.console-hanoi.js ├── Chapter12 ├── express-ajax │ ├── views │ │ ├── error.ejs │ │ └── index.ejs │ ├── public │ │ ├── stylesheets │ │ │ └── style.css │ │ └── ajax.html │ ├── routes │ │ ├── users.js │ │ └── index.js │ └── package.json ├── express-getpost │ ├── views │ │ ├── error.ejs │ │ ├── index.ejs │ │ ├── get.ejs │ │ └── post.ejs │ ├── public │ │ └── stylesheets │ │ │ └── style.css │ ├── routes │ │ ├── users.js │ │ ├── index.js │ │ ├── get.js │ │ └── post.js │ └── package.json ├── express-login │ ├── views │ │ ├── error.ejs │ │ ├── login.ejs │ │ └── index.ejs │ ├── public │ │ └── stylesheets │ │ │ └── style.css │ ├── routes │ │ ├── users.js │ │ ├── index.js │ │ └── login.js │ └── package.json ├── express-routes │ ├── views │ │ ├── error.ejs │ │ ├── about.ejs │ │ ├── name.ejs │ │ ├── pwd.ejs │ │ └── index.ejs │ ├── public │ │ └── stylesheets │ │ │ └── style.css │ ├── routes │ │ ├── users.js │ │ ├── index.js │ │ ├── about.js │ │ ├── pwd.js │ │ └── name.js │ └── package.json ├── express-helloworld │ ├── views │ │ ├── error.ejs │ │ └── index.ejs │ ├── public │ │ └── stylesheets │ │ │ └── style.css │ ├── routes │ │ ├── users.js │ │ └── index.js │ └── package.json ├── createserver │ └── ch12.http_createServer_basic.js ├── requestbasic │ ├── ch12.http_response_basic.js │ └── ch12.http_request_basic.js ├── pingserver │ ├── ch12.http_server_ping.js │ └── ch12.http_client_ping.js ├── redirect │ ├── ch12.http_createServer_redirectB.js │ └── ch12.http_createServer_redirectA.js ├── writeheader │ ├── ch12.http_response_writeheader.js │ └── ch12.http_request_writeheader.js ├── httpget │ ├── ch12.http_response_get.js │ └── ch12.http_request_get.js ├── statuscodes │ └── ch12.http_response_statuscodes.js └── header │ └── ch12.http_response_header.js ├── chapter02 ├── mypackage │ ├── index.js │ ├── lib │ │ ├── main.js │ │ ├── random-a.js │ │ ├── random-b.js │ │ ├── random-c.js │ │ └── sign.js │ ├── package-manual.json │ └── package.json ├── ch02.module-core.js ├── ch02.module-node-modules.js ├── ch02.module-file-circle.js ├── ch02.module-exports-compare-main.js ├── ch02.module-conflict-a.js ├── ch02.module-conflict-b.js ├── ch02.module-exports-main.js ├── ch02.module-conflict-main.js ├── ch02.module-exports-obj.js ├── ch02.module-exchangerate.js ├── ch02.module-exchangerate-obj.js ├── ch02.module-exports-compare-obj.js ├── ch02.module-node.js ├── ch02.module-file.js ├── ch02.module-counter.js ├── ch02.module-counter-obj.js ├── ch02.module-file-foo.js ├── ch02.module-exchangerate-load.js ├── ch02.module-exchangerate-main.js ├── ch02.module-counter-main.js ├── ch02.module-packagejson.json └── ch02.module-load-counter.js ├── chapter04 ├── ch04.buffer.concat │ ├── index.js │ ├── package.json │ └── lib │ │ ├── parse-header-string.js │ │ └── parse-header-buffer.js ├── ch04.buffer-byteLength.js ├── ch04.buffer-toJSON.js ├── ch04.buffer-definesize.js ├── ch04.buffer-isBuffer.js ├── ch04.buffer-slice.js ├── ch04.buffer-copy.js ├── ch04.buffer-toString.js ├── ch04.buffer-concat.js └── ch04.buffer-define.js ├── chapter06 ├── worker.js ├── ch06.child_process_fork_sub.js ├── ch06.child_process_fib_sub.js ├── ch06.child_process_exec_usage.js ├── ch06.child_process_spawn_usage.js ├── ch06.child_process_exec_last.js ├── ch06.child_process_fork_main.js ├── ch06.child_process_fork_usage.js ├── ch06.child_process_execFile_err.js ├── ch06.child_process_execFile_usage.js ├── ch06.child_process_fib_main.js ├── ch06.child_process_spawn_std.js ├── ch06.child_process_spawn_free.js ├── ch06.child_process_exec_std.js ├── ch06.child_process_spawn_ls.js ├── ch06.child_process_spawn_lserr.js ├── ch06.child_process_spawn_pid.js └── ch06.child_process_spawn_ps.js ├── chapter03 ├── ch03.higher-order-func.js ├── ch03.asyn-try-wrong.js ├── ch03.asyn-try-right.js ├── ch03.async-apply.js ├── ch03.asyn-basic.js ├── ch03.async-until.js ├── ch03.async-doUntil.js ├── ch03.partial-func.js ├── ch03.syn-asyn.js ├── ch03.async-series-array.js ├── ch03.async-compose.js ├── ch03.async-series-json.js ├── ch03.async-parallel.js ├── ch03.closure-bak.js ├── ch03.async-parallelLimit.js ├── ch03.async-waterfall.js ├── ch03.async-doWhilst.js ├── ch03.async-auto.js ├── ch03.async-whilst.js ├── ch03.asyn-closure.js ├── ch03.async-queue.js └── ch03.async-iterator.js ├── chapter07 ├── ch07.os_cpus.js ├── ch07.os_hostname.js ├── ch07.os_tmpdir.js ├── ch07.os_arch.js ├── ch07.os_networkInterfaces.js ├── ch07.os_release.js ├── ch07.os_type_platform.js ├── ch07.os_mem.js └── ch07.os_uptime.js ├── .gitattributes ├── Chapter13 ├── ch13.util_isArray.js ├── ch13.util_isDate.js ├── ch13.util_format.js ├── ch13.util_isRegExp.js ├── ch13.util_inspect.js ├── ch13.util_isError.js └── ch13.util_inherits.js ├── chapter10 ├── ServerListening │ └── ch10.net_listening.js ├── ServerClose │ ├── ch10.net_close_client.js │ └── ch10.net_close_server.js ├── SocketAddress │ ├── ch10.net_socketaddr_client.js │ └── ch10.net_socketaddr_server.js ├── SocketRemoteAddress │ ├── ch10.net_remoteaddr_client.js │ └── ch10.net_remoteaddr_server.js ├── connection │ └── ch10.net_connection.js ├── ServerConnection │ ├── ch10.net_connection_client.js │ └── ch10.net_connection_server.js ├── ServerError │ └── ch10.net_error.js ├── ServerGetConnections │ ├── ch10.net_getconnections_clientA.js │ ├── ch10.net_getconnections_clientB.js │ └── ch10.net_getconnections_clientC.js ├── ServerMaxConnections │ ├── ch10.net_maxconnections_clientA.js │ ├── ch10.net_maxconnections_clientB.js │ └── ch10.net_maxconnections_clientC.js ├── client │ └── ch10.net_client.js ├── note │ ├── ch10.net_listening_server.js │ └── ch10.net_listening_client.js ├── ServerClient │ └── ch10.sc_net_client.js ├── SocketData │ ├── ch10.net_socketdata_clientA.js │ ├── ch10.net_socketdata_clientB.js │ ├── ch10.net_socketdata_clientC.js │ ├── ch10.net_socketdata_clientD.js │ └── ch10.net_socketdata_clientE.js ├── SocketWrite │ └── ch10.net_socketwrite_client.js ├── UDPServerClient │ └── ch10.udp_client.js ├── UDPClient │ └── ch10.udp_client.js ├── createServer │ └── ch10.net_createServer.js ├── UDPError │ ├── ch10.udp_error_client.js │ └── ch10.udp_error_server.js ├── ServerAddress │ └── ch10.net_server_address.js ├── UDPBroadcast │ └── ch10.udp_broadcast_client.js ├── UDPServer │ └── ch10.udp_server.js └── SocketTimeout │ └── ch10.net_sockettimeout_client.js └── Chapter14 ├── ch14.mysql_query.js └── ch14.mysql_conn.js /chapter09/test/test.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Chapter11/data/destFile.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chapter08/txt/fchmodSync.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chapter08/txt/watchFile.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chapter08/txt/chmod.txt: -------------------------------------------------------------------------------- 1 | fs.chmod() -------------------------------------------------------------------------------- /chapter08/txt/link.txt: -------------------------------------------------------------------------------- 1 | fs.link() -------------------------------------------------------------------------------- /chapter08/txt/read.txt: -------------------------------------------------------------------------------- 1 | fs.read() -------------------------------------------------------------------------------- /chapter08/txt/truncate.txt: -------------------------------------------------------------------------------- 1 | 123456 -------------------------------------------------------------------------------- /chapter05/stderr.txt: -------------------------------------------------------------------------------- 1 | process.stderr -------------------------------------------------------------------------------- /chapter08/txt/fchmod.txt: -------------------------------------------------------------------------------- 1 | fs.fchmod() -------------------------------------------------------------------------------- /chapter08/txt/ftruncate.txt: -------------------------------------------------------------------------------- 1 | hello worl -------------------------------------------------------------------------------- /chapter08/txt/symlink.txt: -------------------------------------------------------------------------------- 1 | fs.symlink() -------------------------------------------------------------------------------- /chapter08/txt/chmodSync.txt: -------------------------------------------------------------------------------- 1 | fs.chmodSync() -------------------------------------------------------------------------------- /chapter08/txt/linkSync.txt: -------------------------------------------------------------------------------- 1 | fs.linkSync() -------------------------------------------------------------------------------- /chapter08/txt/open.txt: -------------------------------------------------------------------------------- 1 | hello world - open() -------------------------------------------------------------------------------- /chapter08/txt/readFile.txt: -------------------------------------------------------------------------------- 1 | fs.readfile() -------------------------------------------------------------------------------- /chapter08/txt/readSync.txt: -------------------------------------------------------------------------------- 1 | fs.readSync() -------------------------------------------------------------------------------- /chapter08/txt/realpath.txt: -------------------------------------------------------------------------------- 1 | fs.realpath() -------------------------------------------------------------------------------- /chapter08/txt/writeFile.txt: -------------------------------------------------------------------------------- 1 | fs.writeFile() -------------------------------------------------------------------------------- /Chapter11/data/read.txt: -------------------------------------------------------------------------------- 1 | Stream - Readable read() -------------------------------------------------------------------------------- /chapter08/txt/chown.txt: -------------------------------------------------------------------------------- 1 | fs.chown() - file own -------------------------------------------------------------------------------- /chapter08/txt/fchown.txt: -------------------------------------------------------------------------------- 1 | fs.fchown() - file own -------------------------------------------------------------------------------- /chapter08/txt/readFileSync.txt: -------------------------------------------------------------------------------- 1 | fs.readfileSync() -------------------------------------------------------------------------------- /chapter08/txt/realpathSync.txt: -------------------------------------------------------------------------------- 1 | fs.realpathSync() -------------------------------------------------------------------------------- /chapter08/txt/symlinkSync.txt: -------------------------------------------------------------------------------- 1 | fs.symlinkSync() -------------------------------------------------------------------------------- /Chapter11/data/basic.txt: -------------------------------------------------------------------------------- 1 | Node.js - Stream Readable -------------------------------------------------------------------------------- /Chapter11/data/data.txt: -------------------------------------------------------------------------------- 1 | Stream - Readable Data Event -------------------------------------------------------------------------------- /Chapter11/data/readable.txt: -------------------------------------------------------------------------------- 1 | Stream - readable event -------------------------------------------------------------------------------- /chapter08/txt/chownSync.txt: -------------------------------------------------------------------------------- 1 | fs.chownSync() - file own -------------------------------------------------------------------------------- /chapter08/txt/fstat.txt: -------------------------------------------------------------------------------- 1 | fs.fstat() - file information -------------------------------------------------------------------------------- /chapter08/txt/helloworld-asyn.txt: -------------------------------------------------------------------------------- 1 | hello world - asyn -------------------------------------------------------------------------------- /chapter08/txt/helloworld-syn.txt: -------------------------------------------------------------------------------- 1 | hello world - syn -------------------------------------------------------------------------------- /chapter08/txt/openSync.txt: -------------------------------------------------------------------------------- 1 | hello world - openSync() -------------------------------------------------------------------------------- /chapter08/txt/stat.txt: -------------------------------------------------------------------------------- 1 | fs.stat() - file information -------------------------------------------------------------------------------- /chapter08/txt/truncateSync.txt: -------------------------------------------------------------------------------- 1 | 1234567890 - truncate() -------------------------------------------------------------------------------- /chapter08/txt/writeFileSync.txt: -------------------------------------------------------------------------------- 1 | fs.writeFileSync() -------------------------------------------------------------------------------- /Chapter11/data/srcDrain.txt: -------------------------------------------------------------------------------- 1 | Stream - Writable - drain event -------------------------------------------------------------------------------- /chapter08/txt/statSync.txt: -------------------------------------------------------------------------------- 1 | fs.statSync() - file information -------------------------------------------------------------------------------- /Chapter11/data/createReadStream.txt: -------------------------------------------------------------------------------- 1 | Stream - createReadStream() -------------------------------------------------------------------------------- /Chapter11/data/destFinish.txt: -------------------------------------------------------------------------------- 1 | Stream - Writable - finish event -------------------------------------------------------------------------------- /Chapter11/data/srcFinish.txt: -------------------------------------------------------------------------------- 1 | Stream - Writable - finish event -------------------------------------------------------------------------------- /Chapter11/data/writable.txt: -------------------------------------------------------------------------------- 1 | stream - writable - file - end. 2 | -------------------------------------------------------------------------------- /chapter01/error.txt: -------------------------------------------------------------------------------- 1 | Node.js - console.error() and console.warn() -------------------------------------------------------------------------------- /chapter08/txt/fstatSync.txt: -------------------------------------------------------------------------------- 1 | fs.fstatSync() - file information -------------------------------------------------------------------------------- /chapter08/txt/ftruncateSync.txt: -------------------------------------------------------------------------------- 1 | hello world - ftruncateSync() -------------------------------------------------------------------------------- /chapter08/txtlink/symlink.txt: -------------------------------------------------------------------------------- 1 | IntxLNKtxt/symlink.txt -------------------------------------------------------------------------------- /Chapter11/data/pause.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * ch11.stream_readable_pause.js 3 | */ -------------------------------------------------------------------------------- /chapter08/txtlink/symlinkSync.txt: -------------------------------------------------------------------------------- 1 | IntxLNKtxt/symlinkSync.txt -------------------------------------------------------------------------------- /Chapter11/data/srcFile.txt: -------------------------------------------------------------------------------- 1 | Stream - pipe - srcfile.txt 2 | Stream - pipe - destfile.txt -------------------------------------------------------------------------------- /Chapter11/data/destUnFile.txt: -------------------------------------------------------------------------------- 1 | Stream - pipe - srcUnFile.txt 2 | Stream - pipe - destUnFile.txt -------------------------------------------------------------------------------- /Chapter11/data/srcUnFile.txt: -------------------------------------------------------------------------------- 1 | Stream - pipe - srcUnFile.txt 2 | Stream - pipe - destUnFile.txt -------------------------------------------------------------------------------- /Chapter11/data/srcDrain.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingwjz/Node.js-code/HEAD/Chapter11/data/srcDrain.mp3 -------------------------------------------------------------------------------- /chapter08/txt/appendFile.txt: -------------------------------------------------------------------------------- 1 | fs.appendFile(filename, data[, options], callback) 2 | add filename to appendFile.txt 3 | -------------------------------------------------------------------------------- /chapter08/txt/appendFileSync.txt: -------------------------------------------------------------------------------- 1 | fs.appendFileSync(filename, data[, options]) 2 | add filename to appendFileSync.txt 3 | -------------------------------------------------------------------------------- /Chapter12/express-ajax/views/error.ejs: -------------------------------------------------------------------------------- 1 |

<%= message %>

2 |

<%= error.status %>

3 |
<%= error.stack %>
4 | -------------------------------------------------------------------------------- /Chapter12/express-getpost/views/error.ejs: -------------------------------------------------------------------------------- 1 |

<%= message %>

2 |

<%= error.status %>

3 |
<%= error.stack %>
4 | -------------------------------------------------------------------------------- /Chapter12/express-login/views/error.ejs: -------------------------------------------------------------------------------- 1 |

<%= message %>

2 |

<%= error.status %>

3 |
<%= error.stack %>
4 | -------------------------------------------------------------------------------- /Chapter12/express-routes/views/error.ejs: -------------------------------------------------------------------------------- 1 |

<%= message %>

2 |

<%= error.status %>

3 |
<%= error.stack %>
4 | -------------------------------------------------------------------------------- /chapter02/mypackage/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-6. 3 | * 4 | * index.js 5 | */ 6 | var cal = require('./lib/calculate'); -------------------------------------------------------------------------------- /chapter02/mypackage/lib/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-4. 3 | * 4 | * main.js 5 | */ 6 | var cal = require('./calculate'); -------------------------------------------------------------------------------- /chapter08/txt/writeSync.txt: -------------------------------------------------------------------------------- 1 | fs.writeSync(fd, buffer, offset, length[, position]) 2 | fs.writeSync(fd, data[, position[, encoding]]) 3 | -------------------------------------------------------------------------------- /Chapter12/express-helloworld/views/error.ejs: -------------------------------------------------------------------------------- 1 |

<%= message %>

2 |

<%= error.status %>

3 |
<%= error.stack %>
4 | -------------------------------------------------------------------------------- /chapter04/ch04.buffer.concat/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-6. 3 | * 4 | * index.js 5 | */ 6 | var cal = require('./lib/main'); -------------------------------------------------------------------------------- /chapter08/txt/write.txt: -------------------------------------------------------------------------------- 1 | fs.write(fd, buffer, offset, length[, position], callback) 2 | fs.write(fd, data[, position[, encoding]], callback) 3 | -------------------------------------------------------------------------------- /chapter01/ch01.hello-world.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/12. 3 | * 4 | * ch01.hello-world.js 5 | */ 6 | console.log("Hello World!"); -------------------------------------------------------------------------------- /chapter02/ch02.module-core.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-core.js 5 | */ 6 | var http = require('http'); // TODO: 加载核心模块'http' -------------------------------------------------------------------------------- /chapter06/worker.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-7. 3 | * 4 | * ch06.child_process_fork_usage.js worker.js 5 | */ 6 | console.info('This is a child_process.'); -------------------------------------------------------------------------------- /Chapter12/express-ajax/public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00B7FF; 8 | } -------------------------------------------------------------------------------- /Chapter12/express-getpost/public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00B7FF; 8 | } -------------------------------------------------------------------------------- /Chapter12/express-login/public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00B7FF; 8 | } -------------------------------------------------------------------------------- /Chapter12/express-routes/public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00B7FF; 8 | } -------------------------------------------------------------------------------- /Chapter12/express-helloworld/public/stylesheets/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 50px; 3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 4 | } 5 | 6 | a { 7 | color: #00B7FF; 8 | } -------------------------------------------------------------------------------- /chapter01/ch01.log-info.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/20. 3 | * 4 | * ch01.log-info.js 5 | */ 6 | console.log("Node.js - console.log() 方法"); 7 | console.info("Node.js - console.info() 方法"); -------------------------------------------------------------------------------- /chapter01/ch01.console-assert.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/15. 3 | * 4 | * ch01.console-assert.js 5 | */ 6 | var i=0; 7 | var j=1; 8 | console.assert(i==0, "OK"); 9 | console.assert(i==j, "throw an exception"); -------------------------------------------------------------------------------- /chapter01/ch01.obj-dir.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/6. 3 | * 4 | * ch01.obj-dir.js 5 | */ 6 | console.dir(123); 7 | console.dir("abc"); 8 | console.dir({"abc":123}); 9 | console.dir(1+2*3+1); 10 | console.dir(console); -------------------------------------------------------------------------------- /chapter03/ch03.higher-order-func.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch03.higher-order-func.js 5 | */ 6 | var arrSort = [5,34,87,32,56,2,17]; 7 | arrSort.sort(function(a,b){ 8 | return b-a; 9 | }); 10 | console.info(arrSort); -------------------------------------------------------------------------------- /chapter02/ch02.module-node-modules.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-node-modules.js 5 | */ 6 | console.log(); 7 | console.log('---打印paths属性---'); 8 | console.log(module.paths); 9 | console.log('---打印完成---'); 10 | console.log(); -------------------------------------------------------------------------------- /Chapter12/express-ajax/routes/users.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var router = express.Router(); 3 | 4 | /* GET users listing. */ 5 | router.get('/', function(req, res, next) { 6 | res.send('respond with a resource'); 7 | }); 8 | 9 | module.exports = router; 10 | -------------------------------------------------------------------------------- /Chapter12/express-login/routes/users.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var router = express.Router(); 3 | 4 | /* GET users listing. */ 5 | router.get('/', function(req, res, next) { 6 | res.send('respond with a resource'); 7 | }); 8 | 9 | module.exports = router; 10 | -------------------------------------------------------------------------------- /Chapter12/express-getpost/routes/users.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var router = express.Router(); 3 | 4 | /* GET users listing. */ 5 | router.get('/', function(req, res, next) { 6 | res.send('respond with a resource'); 7 | }); 8 | 9 | module.exports = router; 10 | -------------------------------------------------------------------------------- /Chapter12/express-helloworld/routes/users.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var router = express.Router(); 3 | 4 | /* GET users listing. */ 5 | router.get('/', function(req, res, next) { 6 | res.send('respond with a resource'); 7 | }); 8 | 9 | module.exports = router; 10 | -------------------------------------------------------------------------------- /chapter02/ch02.module-file-circle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-28. 3 | * 4 | * ch02.module-file-circle.js 5 | */ 6 | var PI = Math.PI; 7 | exports.area = function(r) { 8 | return PI * r * r; 9 | }; 10 | exports.circumference = function(r) { 11 | return 2 * PI * r; 12 | }; -------------------------------------------------------------------------------- /Chapter12/express-routes/views/about.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

About <%= title %>

10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter12/express-routes/views/name.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Name: <%= name %>

10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter12/express-routes/views/pwd.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

PWD: <%= passwd %>

10 | 11 | 12 | -------------------------------------------------------------------------------- /chapter02/mypackage/package-manual.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mypackage", 3 | "description": "mypackage - 简单四则运算应用", 4 | "main": "./lib/main", 5 | "author": { 6 | "name": "king" 7 | }, 8 | "version": "0.0.1", 9 | "dependencies": { 10 | }, 11 | "devDependencies": { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter12/express-routes/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 | 11 | 12 | -------------------------------------------------------------------------------- /Chapter12/express-getpost/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 | 11 | 12 | -------------------------------------------------------------------------------- /chapter05/ch05.process-cwd.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-cmd.js 5 | */ 6 | console.info("------ Process cwd ------"); 7 | console.info(); 8 | console.log('Current directory: ' + process.cwd()); 9 | console.info(); 10 | console.info("------ Process cwd ------"); 11 | -------------------------------------------------------------------------------- /chapter01/ch01.format-data.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/20. 3 | * 4 | * ch01.format-data.js 5 | */ 6 | console.log(8) 7 | console.log(8, 8+0.8); 8 | console.log("%d", 8, 8.8); 9 | console.log("%d-%d", 8.8, 8.0); 10 | console.log("%d", 8+8, 8-8, 8*8, 8/8); 11 | console.log("%d", "8+8"); 12 | console.log(8/0); -------------------------------------------------------------------------------- /chapter01/ch01.format-logic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/22. 3 | * 4 | * ch01.format-logic.js 5 | */ 6 | var a=0; 7 | var b=1; 8 | console.log(a==b); // 使用比较运算符,输出false 9 | console.log(a>=b); // 使用比较运算符,输出false 10 | console.log(a<=b); // 使用比较运算符,输出true 11 | console.log(a==0 && b==1); // 使用逻辑运算符,输出true -------------------------------------------------------------------------------- /chapter01/ch01.time-timeend.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/7. 3 | * 4 | * ch01.time-timeend.js 5 | */ 6 | var n=0; 7 | console.time('10000x10000-times'); 8 | for(var i=0; i<10000; i++) { 9 | for(var j=0; j<10000; j++) { 10 | n++; 11 | } 12 | } 13 | console.timeEnd('10000x10000-times'); 14 | console.info(n); -------------------------------------------------------------------------------- /chapter02/ch02.module-exports-compare-main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exports-compare-main.js 5 | */ 6 | console.log(); 7 | var obj = require('./ch02.module-exports-compare-obj.js'); 8 | var user = new obj('king', 26); 9 | user.userinfo(); 10 | console.log(user.tag); 11 | console.log(); -------------------------------------------------------------------------------- /chapter02/ch02.module-conflict-a.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-conflict-a.js 5 | */ 6 | console.log('a starting'); 7 | exports.done = false; 8 | var b = require('./ch02.module-conflict-b.js'); 9 | console.log('in a, b.done = %j', b.done); 10 | exports.done = true; 11 | console.log('a done'); -------------------------------------------------------------------------------- /chapter02/ch02.module-conflict-b.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-conflict-b.js 5 | */ 6 | console.log('b starting'); 7 | exports.done = false; 8 | var a = require('./ch02.module-conflict-a.js'); 9 | console.log('in b, a.done = %j', a.done); 10 | exports.done = true; 11 | console.log('b done'); -------------------------------------------------------------------------------- /chapter01/ch01.format-argument.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/23. 3 | * 4 | * ch01.format-argument.js 5 | */ 6 | console.log("%s", "argument"); 7 | console.log("%s"); 8 | console.log("%d", 8); 9 | console.log("%d"); 10 | console.log("%8s"); 11 | console.log("%8d"); 12 | console.log("%8s", "%8s"); 13 | console.log("%8d", 8); -------------------------------------------------------------------------------- /chapter07/ch07.os_cpus.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_cpus.js 5 | */ 6 | console.info("------ OS cpus() ------"); 7 | console.info(); 8 | var os = require('os'); // TODO: 引入OS模块 9 | var cpus = os.cpus(); 10 | console.info(cpus); 11 | console.info(); 12 | console.info("------ OS cpus() ------"); -------------------------------------------------------------------------------- /Chapter12/express-ajax/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 |

Click to ajax.html

11 | 12 | 13 | -------------------------------------------------------------------------------- /chapter01/ch01.format-json.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/21. 3 | * 4 | * ch01.format-json.js 5 | */ 6 | console.log("%j", {OS:"Windows",Version:"7.1",Language:["English","Chinese"]}); 7 | var v_json = { 8 | OS:"Windows", 9 | Version:"7.1", 10 | Language:["English","Chinese"] 11 | } 12 | console.log("%j", v_json); 13 | -------------------------------------------------------------------------------- /chapter02/ch02.module-exports-main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exports-main.js 5 | */ 6 | console.log(); 7 | var obj = require('./ch02.module-exports-obj.js'); 8 | obj.on('ready', function() { 9 | console.log('module ch02.module-exports-obj.js is ready'); 10 | console.log(); 11 | }); 12 | console.log(); -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-shell.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-shell.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('指向当前shell的环境变量:'); 9 | console.info(process.env); 10 | console.info(); 11 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /chapter07/ch07.os_hostname.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-14. 3 | * 4 | * ch07.os_hostname.js 5 | */ 6 | console.info("------ OS hostname() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var hostname = os.hostname(); 10 | console.info('操作系统主机名: ' + hostname); 11 | console.info(); 12 | console.info("------ OS hostname() ------"); -------------------------------------------------------------------------------- /chapter02/mypackage/lib/random-a.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-4. 3 | * 4 | * random-a.js 5 | */ 6 | var a; 7 | console.info('随机生成100以内的整数...'); 8 | /** 9 | * exports random a 10 | * @returns {number} 11 | */ 12 | exports.generate_a = function() { 13 | a = Math.round(Math.random() * 100); // TODO: 随机生成100以内的整数 14 | return a.toString(); 15 | } -------------------------------------------------------------------------------- /chapter02/mypackage/lib/random-b.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-4. 3 | * 4 | * random-b.js 5 | */ 6 | var b; 7 | console.info('随机生成100以内的整数...'); 8 | /** 9 | * exports random b 10 | * @returns {number} 11 | */ 12 | exports.generate_b = function() { 13 | b = Math.round(Math.random() * 100); // TODO: 随机生成100以内的整数 14 | return b.toString(); 15 | } -------------------------------------------------------------------------------- /chapter02/mypackage/lib/random-c.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-4. 3 | * 4 | * random-c.js 5 | */ 6 | var c; 7 | console.info('随机生成100以内的整数...'); 8 | /** 9 | * exports random c 10 | * @returns {number} 11 | */ 12 | exports.generate_c = function() { 13 | c = Math.round(Math.random() * 100); // TODO: 随机生成100以内的整数 14 | return c.toString(); 15 | } -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-nodeconfig.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-nodeconfig.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('Node.js配置选项:'); 9 | console.info(process.config); 10 | console.info(); 11 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /chapter02/ch02.module-conflict-main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-conflict-main.js 5 | */ 6 | console.log(); 7 | console.log('main starting'); 8 | var a = require('./ch02.module-conflict-a.js'); 9 | var b = require('./ch02.module-conflict-b.js'); 10 | console.log('in main, a.done=%j, b.done=%j', a.done, b.done); 11 | console.log(); -------------------------------------------------------------------------------- /chapter03/ch03.asyn-try-wrong.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch03.asyn-try-wrong.js 5 | */ 6 | console.info('------ Node.js异步编程:异常捕获! ------'); 7 | /** 8 | * 错误方式 9 | */ 10 | try{ 11 | setTimeout(function(){ 12 | var data = a/0; // TODO: 错误的计算 13 | },1000); 14 | }catch (e){ 15 | console.log(e); 16 | } 17 | console.info(); -------------------------------------------------------------------------------- /Chapter12/express-login/views/login.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 |

User id: <%= userid %>

11 |

Password: <%= pwd %>

12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter12/express-getpost/views/get.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 |

Name(GET): <%= name %>

11 |

Email(GET): <%= email %>

12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter12/express-routes/routes/users.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET users listing 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.send('respond with a resource'); 12 | }); 13 | /** 14 | * 输出模型router 15 | */ 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /chapter03/ch03.asyn-try-right.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/18. 3 | * 4 | * ch03.asyn-try-right.js 5 | */ 6 | console.info('------ Node.js异步编程:异常捕获! ------'); 7 | /** 8 | * 正确方式 9 | */ 10 | setTimeout(function(){ 11 | try{ 12 | var data = b/0; // TODO: 错误的计算 13 | }catch(e){ 14 | console.log(e); 15 | } 16 | },1000); 17 | console.info(); -------------------------------------------------------------------------------- /chapter07/ch07.os_tmpdir.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-14. 3 | * 4 | * ch07.os_tmpdir.js 5 | */ 6 | console.info("------ OS tmpdir() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var type = os.type(); 10 | var tmpdir = os.tmpdir(); 11 | console.info('当前' + type + '系统临时目录: ' + tmpdir); 12 | console.info(); 13 | console.info("------ OS tmpdir() ------"); -------------------------------------------------------------------------------- /Chapter12/express-getpost/views/post.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 |

Name(POST): <%= name %>

11 |

Email(POST): <%= email %>

12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter12/express-helloworld/routes/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET home page. 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.render('index', { title: 'Express' }); 12 | }); 13 | /** 14 | * 输出模型router 15 | */ 16 | module.exports = router; 17 | -------------------------------------------------------------------------------- /chapter02/ch02.module-exports-obj.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/2. 3 | * 4 | * ch02.module-exports-obj.js 5 | */ 6 | var EventEmitter = require('events').EventEmitter; 7 | module.exports = new EventEmitter(); 8 | // Do some work, and after some time emit the 'ready' event from the module itself. 9 | setTimeout(function() { 10 | module.exports.emit('ready'); 11 | }, 1000); -------------------------------------------------------------------------------- /Chapter12/express-ajax/routes/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET root page. 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.render('index', { 12 | title: 'Express - Ajax' 13 | }); 14 | }); 15 | /** 16 | * 输出模型router 17 | */ 18 | module.exports = router; 19 | -------------------------------------------------------------------------------- /chapter02/mypackage/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mypackage", 3 | "version": "0.0.1", 4 | "description": "mypackage - calculate app", 5 | "main": "./lib/main.js", 6 | "directories": { 7 | "doc": "doc", 8 | "test": "test" 9 | }, 10 | "scripts": { 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "author": "king", 14 | "license": "BSD-2-Clause" 15 | } 16 | -------------------------------------------------------------------------------- /Chapter12/express-login/routes/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET root page. 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.render('index', { 12 | title: 'Express - Login' 13 | }); 14 | }); 15 | /** 16 | * 输出模型router 17 | */ 18 | module.exports = router; 19 | -------------------------------------------------------------------------------- /Chapter12/express-routes/routes/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET root page. 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.render('index', { 12 | title: 'Express - Routes' 13 | }); 14 | }); 15 | /** 16 | * 输出模型router 17 | */ 18 | module.exports = router; 19 | -------------------------------------------------------------------------------- /chapter07/ch07.os_arch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_arch.js 5 | */ 6 | console.info("------ OS arch() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var platform = os.platform(); 10 | console.info('操作系统平台: ' + platform); 11 | var arch = os.arch(); 12 | console.info('操作系统架构: ' + arch); 13 | console.info(); 14 | console.info("------ OS arch() ------"); -------------------------------------------------------------------------------- /Chapter12/express-getpost/routes/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET root page. 9 | */ 10 | router.get('/', function(req, res, next) { 11 | res.render('index', { 12 | title: 'Express - GET/POST' 13 | }); 14 | }); 15 | /** 16 | * 输出模型router 17 | */ 18 | module.exports = router; 19 | -------------------------------------------------------------------------------- /Chapter12/express-routes/routes/about.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET about page. 9 | */ 10 | router.get('/about', function(req, res, next) { 11 | res.render('about', { 12 | title: 'Express - Routes' 13 | }); 14 | }); 15 | /** 16 | * 输出模型router 17 | */ 18 | module.exports = router; -------------------------------------------------------------------------------- /chapter04/ch04.buffer.concat/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ch04.buffer.concat", 3 | "version": "0.0.1", 4 | "description": "package - ch04.buffer.concat", 5 | "main": "./lib/main.js", 6 | "directories": { 7 | "doc": "doc", 8 | "test": "test" 9 | }, 10 | "scripts": { 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "author": "king", 14 | "license": "BSD-2-Clause" 15 | } 16 | -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-pid.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-pid.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('当前进程id:'); 9 | console.info(process.pid); 10 | console.info(); 11 | console.info('当前进程名称:'); 12 | console.info(process.title); 13 | console.info(); 14 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /chapter07/ch07.os_networkInterfaces.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_networkInterfaces.js 5 | */ 6 | console.info("------ OS os_networkInterfaces() ------"); 7 | console.info(); 8 | var os = require('os'); // TODO: 引入OS模块 9 | var networkInterfaces = os.networkInterfaces(); 10 | console.info(networkInterfaces); 11 | console.info(); 12 | console.info("------ OS os_networkInterfaces() ------"); -------------------------------------------------------------------------------- /Chapter12/express-ajax/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-ajax", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./bin/www" 7 | }, 8 | "dependencies": { 9 | "body-parser": "~1.12.4", 10 | "cookie-parser": "~1.3.5", 11 | "debug": "~2.2.0", 12 | "ejs": "~2.3.1", 13 | "express": "~4.12.4", 14 | "morgan": "~1.5.3", 15 | "serve-favicon": "~2.2.1" 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter12/express-login/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-login", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./bin/www" 7 | }, 8 | "dependencies": { 9 | "body-parser": "~1.12.4", 10 | "cookie-parser": "~1.3.5", 11 | "debug": "~2.2.0", 12 | "ejs": "~2.3.1", 13 | "express": "~4.12.4", 14 | "morgan": "~1.5.3", 15 | "serve-favicon": "~2.2.1" 16 | } 17 | } -------------------------------------------------------------------------------- /chapter02/ch02.module-exchangerate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exchangerate.js 5 | */ 6 | // 使用module模块的exports方法导出rmb2dollar函数 7 | exports.rmb2dollar = function (m) { 8 | return m / 6.2467 + " US Dollar"; // 将人民币按照最新汇率换算成美元并返回 9 | }; 10 | // 使用module模块的exports方法导出dollar2rmb函数 11 | exports.dollar2rmb = function (m) { 12 | return m * 6.2467 + " Yuan of PRC"; // 将美元按照最新汇率换算成人民币并返回 13 | }; -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-cpu.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-cpu.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('当前系统平台:'); 9 | console.info(process.platform); 10 | console.info(); 11 | console.info('当前CPU架构:'); 12 | console.info(process.arch); 13 | console.info(); 14 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /Chapter12/express-getpost/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-getpost", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./bin/www" 7 | }, 8 | "dependencies": { 9 | "body-parser": "~1.12.4", 10 | "cookie-parser": "~1.3.5", 11 | "debug": "~2.2.0", 12 | "ejs": "~2.3.1", 13 | "express": "~4.12.4", 14 | "morgan": "~1.5.3", 15 | "serve-favicon": "~2.2.1" 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter12/express-routes/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-routes", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./bin/www" 7 | }, 8 | "dependencies": { 9 | "body-parser": "~1.12.4", 10 | "cookie-parser": "~1.3.5", 11 | "debug": "~2.2.0", 12 | "ejs": "~2.3.1", 13 | "express": "~4.12.4", 14 | "morgan": "~1.5.3", 15 | "serve-favicon": "~2.2.1" 16 | } 17 | } -------------------------------------------------------------------------------- /chapter03/ch03.async-apply.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-apply.js 5 | */ 6 | apply(function, arguments..) 7 | apply是一个非常好用的函数,可以让我们给一个函数预绑定多个参数并生成一个可直接调用的新函数,简化代码。示例如下: 8 | 9 | function(callback) { 10 | test(3, callback); 11 | }; 12 | 用apply改写: 13 | async.apply(test, 3); 14 | log是通过为console.log函数预设了一个参数'> '而得到的新函数,其输出格式为'> ****',请实现log函数,并调用它输出'> good'; 15 | 16 | //apply是个非常实用的函数,运用得当会减少很多基础工作。 -------------------------------------------------------------------------------- /chapter07/ch07.os_release.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_release.js 5 | */ 6 | console.info("------ OS release() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var type = os.type(); 10 | console.info('操作系统类型: ' + type); 11 | console.info(); 12 | var release = os.release(); 13 | console.info('操作系统发行版本: ' + release); 14 | console.info(); 15 | console.info("------ OS release() ------"); -------------------------------------------------------------------------------- /Chapter12/express-helloworld/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-helloworld", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "node ./bin/www" 7 | }, 8 | "dependencies": { 9 | "body-parser": "~1.12.4", 10 | "cookie-parser": "~1.3.5", 11 | "debug": "~2.2.0", 12 | "ejs": "~2.3.1", 13 | "express": "~4.12.4", 14 | "morgan": "~1.5.3", 15 | "serve-favicon": "~2.2.1" 16 | } 17 | } -------------------------------------------------------------------------------- /chapter01/ch01.stderr-file.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/6. 3 | * 4 | * ch01.stderr-file.js 5 | */ 6 | var fs = require('fs'); 7 | var file = 'chapter01/not-found.txt'; 8 | var encoding = 'UTF-8'; 9 | fs.readFile(file, encoding, function(err, data) { 10 | if(err) { 11 | console.error("error - \n %s", err); 12 | console.warn("warn - \n %s", err); 13 | } else { 14 | console.log(data); 15 | } 16 | }); -------------------------------------------------------------------------------- /chapter02/ch02.module-exchangerate-obj.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exchangerate-obj.js 5 | */ 6 | // 使用module模块的exports方法导出rmb2dollar函数 7 | exports.rmb2dollar = function (m) { 8 | return m / 6.2467 + " US Dollar"; // 将人民币按照最新汇率换算成美元并返回 9 | }; 10 | // 使用module模块的exports方法导出dollar2rmb函数 11 | exports.dollar2rmb = function (m) { 12 | return m * 6.2467 + " Yuan of PRC"; // 将美元按照最新汇率换算成人民币并返回 13 | }; -------------------------------------------------------------------------------- /chapter02/ch02.module-exports-compare-obj.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/2. 3 | * 4 | * ch02.module-exports-compare-obj.js 5 | */ 6 | module.exports = function(name, age) { 7 | this.name = name; 8 | this.age = age; 9 | this.userinfo = function() { 10 | console.log(this.name +' is '+ this.age +' years old'); 11 | }; 12 | }; 13 | exports.tag = function() { 14 | console.log('This is a tag function.'); 15 | }; -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-node.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-node.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('Node.js版本号:'); 9 | console.info(process.version); 10 | console.info(); 11 | console.info('Node.js版本属性:'); 12 | console.info(process.versions); 13 | console.info(); 14 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /chapter01/ch01.error-warn.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/23. 3 | * 4 | * ch01.error-warn.js 5 | */ 6 | var fs = require('fs'); 7 | var file = 'chapter01/error-warn.txt'; 8 | var encoding = 'UTF-8'; 9 | fs.readFile(file, encoding, function(err, data) { 10 | if(err) { 11 | console.error("error - \n %s", err); 12 | console.warn("warn - \n %s", err); 13 | } else { 14 | console.log(data); 15 | } 16 | }); -------------------------------------------------------------------------------- /chapter05/ch05.process-chdir-win.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-chdir-win.js 5 | */ 6 | console.info("------ Process chdir ------"); 7 | console.info(); 8 | console.log('Current directory: ' + process.cwd()); 9 | console.log('Change directory to: h:\\'); 10 | process.chdir('h:\\'); 11 | console.log('Current directory: ' + process.cwd()); 12 | console.info(); 13 | console.info("------ Process chdir ------"); -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo-process.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo-process.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('运行当前进程可执行文件的绝对路径:'); 9 | console.info(process.execPath); 10 | console.info(); 11 | console.info('当前进程的命令行参数数组:'); 12 | console.info(process.argv); 13 | console.info(); 14 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /Chapter12/express-routes/routes/pwd.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET pwd page. 9 | */ 10 | router.get('/pwd/:passwd', function(req, res, next) { 11 | res.render('pwd', { 12 | title: 'Express - Routes', 13 | passwd: req.params.passwd 14 | }); 15 | }); 16 | /** 17 | * 输出模型router 18 | */ 19 | module.exports = router; -------------------------------------------------------------------------------- /chapter05/ch05.process-chdir.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-chdir.js 5 | */ 6 | console.info("------ Process chdir ------"); 7 | console.info(); 8 | console.log('Current directory: ' + process.cwd()); 9 | console.log('Change directory to: /home/king'); 10 | process.chdir('/home/king'); 11 | console.log('Current directory: ' + process.cwd()); 12 | console.info(); 13 | console.info("------ Process chdir ------"); -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /chapter04/ch04.buffer-byteLength.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-byteLength.js 5 | */ 6 | console.info("------Buffer.byteLength()------"); 7 | console.info(); 8 | str = '\u00bd + \u00bc = \u00be'; // TODO: 定义字符串 9 | // TODO: ½ + ¼ = ¾: 9 characters, 12 bytes 10 | console.log(str + ": " + str.length + " characters, " + Buffer.byteLength(str, 'utf8') + " bytes"); 11 | console.info(); 12 | console.info("------Buffer.byteLength()------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readdirSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-28. 3 | * 4 | * ch08.fs_readdirSync.js 5 | */ 6 | console.info("------ fs readdirSync() ------"); 7 | console.info(); 8 | var path = "txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | var files = fs.readdirSync(path); // TODO: 读取文件目录(同步方式) 11 | console.info('read directory txt: '); 12 | console.info(files); // TODO: 打印输出文件目录 13 | console.log('fs.readdirSync() Done.'); 14 | console.info(); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_fork_sub.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_fork_sub.js 5 | */ 6 | console.info("------ child_process fork sub ------"); 7 | console.info(); 8 | /** 9 | * process on message 10 | */ 11 | process.on('message', function(m) { 12 | console.log('CHILD got message:', m); 13 | }); 14 | /** 15 | * process send message 16 | */ 17 | process.send({ sub: 'main' }); // TODO: send message 18 | console.info(); -------------------------------------------------------------------------------- /chapter07/ch07.os_type_platform.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-14. 3 | * 4 | * ch07.os_type_platform.js 5 | */ 6 | console.info("------ OS type() & platfrom() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var type = os.type(); 10 | console.info('当前操作系统类型为: ' + type); 11 | console.info(); 12 | var platform = os.platform(); 13 | console.info('当前操作系统平台为: ' + platform); 14 | console.info(); 15 | console.info("------ OS type() & platfrom() ------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_statSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_statSync.js 5 | */ 6 | console.info("------ fs statSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var statSync = fs.statSync('txt/statSync.txt'); // TODO: 获取文件信息(同步方法) 10 | console.info('txt/statSync.txt file info: '); 11 | console.info(statSync); // TODO: 打印输出文件信息 12 | console.info(); 13 | console.info('fs.statSync() Done.'); 14 | console.info(); -------------------------------------------------------------------------------- /Chapter12/express-routes/routes/name.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET name page. 9 | * with req.query.name parameters 10 | */ 11 | router.get('/name', function(req, res) { 12 | res.render('name', { 13 | title: 'Express - Routes', 14 | name: req.query.name 15 | }); 16 | }); 17 | /** 18 | * 输出模型router 19 | */ 20 | module.exports = router; -------------------------------------------------------------------------------- /chapter01/ch01.console-narcissus.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/5. 3 | * 4 | * ch01.console-narcissus.js 5 | */ 6 | var m, a, b, c, sum; 7 | for(m=100; m<1000; m++) { // 循环判断100~999整数中的水仙花数 8 | a = parseInt(m/100); // 计算出百位数 9 | b = parseInt((m-a*100)/10); // 计算出十位数 10 | c = parseInt(m-a*100-b*10); // 计算出个位数 11 | sum = a*a*a + b*b*b + c*c*c; 12 | if(m == sum) { // 判断是否满足水仙花规则 13 | console.info("%d", m); 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter12/express-getpost/routes/get.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET get page. 9 | */ 10 | router.get('/get', function(req, res, next) { 11 | res.render('get', { 12 | title: 'Express - GET/POST', 13 | name: req.query.name, 14 | email: req.query.email 15 | }); 16 | }); 17 | /** 18 | * 输出模型router 19 | */ 20 | module.exports = router; 21 | -------------------------------------------------------------------------------- /chapter03/ch03.asyn-basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-11. 3 | * 4 | * ch03.asyn-basic.js 5 | */ 6 | console.info('------ Node.js异步编程:基础初步! ------'); 7 | console.info("\n"); 8 | // 使用setTimeout()异步方法初探异步机制 9 | setTimeout(function(){ 10 | console.log('asyn - print it now!'); // 在回调函数内输出信息 11 | },3000); 12 | console.log('asyn - print it 3 second later!'); // 异步方法后输出信息 13 | console.info("\n"); 14 | console.info('------ Node.js异步编程 ------'); 15 | console.info("\n"); -------------------------------------------------------------------------------- /Chapter12/express-getpost/routes/post.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET post page. 9 | */ 10 | router.post('/post', function(req, res, next) { 11 | res.render('post', { 12 | title: 'Express - GET/POST', 13 | name: req.body.name, 14 | email: req.body.email 15 | }); 16 | }); 17 | /** 18 | * 输出模型router 19 | */ 20 | module.exports = router; 21 | -------------------------------------------------------------------------------- /Chapter12/express-login/routes/login.js: -------------------------------------------------------------------------------- 1 | /** 2 | * module define 3 | * @type {*|exports} 4 | */ 5 | var express = require('express'); 6 | var router = express.Router(); 7 | /** 8 | * GET login page. 9 | */ 10 | router.post('/login', function(req, res, next) { 11 | res.render('login', { 12 | title: 'Express - Login', 13 | userid: req.body.userid, 14 | pwd: req.body.pwd 15 | }); 16 | }); 17 | /** 18 | * 输出模型router 19 | */ 20 | module.exports = router; 21 | -------------------------------------------------------------------------------- /chapter02/ch02.module-node.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | */ 4 | 从node_modules文件夹中加载# 5 | 6 | 如果require()中的模块名不是一个本地模块,也没有以'/', '../', 或是 './'开头,那么node会从当前模块的父目录开始,尝试在它的/node_modules文件夹里加载相应模块。 7 | 8 | 如果没有找到,那么就再向上移动到父目录,直到到达顶层目录位置。 9 | 10 | 例如,如果位于'/home/ry/projects/foo.js'的文件调用了require('bar.js'),那么node查找的位置依次为: 11 | 12 | /home/ry/projects/node_modules/bar.js 13 | /home/ry/node_modules/bar.js 14 | /home/node_modules/bar.js 15 | /node_modules/bar.js 16 | 17 | 这就要求程序员应尽量把依赖放在就近的位置,以防崩溃。 -------------------------------------------------------------------------------- /Chapter13/ch13.util_isArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_isArray.js 5 | */ 6 | console.info("------ util isArray() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * return value is true 11 | */ 12 | console.log(util.inspect(util.isArray([]))); 13 | /** 14 | * return value is true 15 | */ 16 | console.log(util.inspect(util.isArray(new Array))); 17 | /** 18 | * return value is false 19 | */ 20 | console.log(util.inspect(util.isArray({}))); -------------------------------------------------------------------------------- /Chapter13/ch13.util_isDate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_isDate.js 5 | */ 6 | console.info("------ util isDate() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * return value is true 11 | */ 12 | console.log(util.inspect(util.isDate(new Date()))); 13 | /** 14 | * return value is false 15 | */ 16 | console.log(util.inspect(util.isDate(Date()))); 17 | /** 18 | * return value is false 19 | */ 20 | console.log(util.inspect(util.isDate({}))); -------------------------------------------------------------------------------- /chapter03/ch03.async-until.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-until.js 5 | */ 6 | var async = require('async'); 7 | var count = 5; 8 | async.until( 9 | function () { return count < 0; }, 10 | function (callback) { 11 | count--; 12 | setTimeout(callback, 1000); 13 | }, 14 | function (err) { 15 | console.log(); 16 | } 17 | ); 18 | //until(test, fn, callback) 19 | //until与whilst正好相反,当test条件函数返回值为false时继续循环,与true时跳出。其它特性一致。 20 | //和whilst类似的效果,根据实际需要选择until或whilst。 -------------------------------------------------------------------------------- /Chapter13/ch13.util_format.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_format.js 5 | */ 6 | console.info("------ util format() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * return value is 'foo:%s' 11 | */ 12 | console.info(util.format('%s:%s', 'foo')); 13 | /** 14 | * return value is 'foo:bar baz' 15 | */ 16 | console.info(util.format('%s:%s', 'foo', 'bar', 'baz')); 17 | /** 18 | * return value is '1 2 3' 19 | */ 20 | console.info(util.format(1, 2, 3)); -------------------------------------------------------------------------------- /chapter03/ch03.async-doUntil.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-doUntil.js 5 | */ 6 | var async = require('async'); 7 | var count = 5; 8 | async.doUntil( 9 | function (callback) { 10 | count--; 11 | setTimeout(callback, 1000); 12 | }, 13 | function () { return count < 0; }, 14 | function (err) { 15 | console.log(); 16 | } 17 | ); 18 | //doUntil(fn, test, callback) 19 | //doUntil与doWhilst正好相反,当test为false时循环,与true时跳出。其它特性一致。 20 | //和doWhilst类似的效果,根据实际需要选择doUntil或doWhilst。 -------------------------------------------------------------------------------- /chapter06/ch06.child_process_fib_sub.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_fib_sub.js 5 | */ 6 | console.info("------ child_process fork sub ------"); 7 | console.info(); 8 | /** 9 | * function fib 10 | */ 11 | function fib(n) { 12 | if (n < 2) { 13 | return 1; 14 | } else { 15 | return fib(n - 2) + fib(n - 1); 16 | } 17 | } 18 | /** 19 | * process send message 20 | */ 21 | process.on('message', function(m) { 22 | process.send({result: fib(m.input)}); // TODO: send message 23 | }); -------------------------------------------------------------------------------- /chapter01/ch01.format-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2014/12/20. 3 | * 4 | * ch01-format-string.js 5 | */ 6 | console.log("%s", "This is a format-string Note.js Program."); /* %s - String */ 7 | console.log("%s %s %s", "You can", "connect", "several strings."); /* connect strings */ 8 | console.log("%s", "You can", "connect", "several strings."); 9 | console.log("%s:%s", "object", "string"); 10 | console.log("%s-%s", "object", "string"); 11 | console.log("%"); 12 | console.log("%%"); /* single percent sign ('%'). This does not consume an argument. */ -------------------------------------------------------------------------------- /chapter02/ch02.module-file.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | */ 4 | 如果按文件名没有查找到,那么node会添加 .js和 .json后缀名,再尝试加载,如果还是没有找到,最后会加上.node的后缀名再次尝试加载。 5 | 6 | .js 会被解析为Javascript纯文本文件,.json 会被解析为JSON格式的纯文本文件. .node 则会被解析为编译后的插件模块,由dlopen进行加载。 7 | 8 | 模块以'/'为前缀,则表示绝对路径。例如,require('/home/marco/foo.js') ,加载的是/home/marco/foo.js这个文件。 9 | 10 | 模块以'./'为前缀,则路径是相对于调用require()的文件。 也就是说,circle.js必须和foo.js在同一目录下,require('./circle')才能找到。 11 | 12 | 当没有以'/'或者'./'来指向一个文件时,这个模块要么是"核心模块",要么就是从node_modules文件夹加载的。 13 | 14 | 如果指定的路径不存在,require()会抛出一个code属性为'MODULE_NOT_FOUND'的错误。 -------------------------------------------------------------------------------- /chapter03/ch03.partial-func.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch03.partial-func.js 5 | */ 6 | var isType = function(type){ 7 | return function(obj){ 8 | return toString.call(obj)=='[object '+type+']'; 9 | } 10 | }; 11 | var isString = isType('String'); 12 | var isFunction = isType('Function'); 13 | var isArray= isType('Array'); 14 | 15 | 16 | 17 | var say =function(name){ 18 | return function(text){ 19 | console.log(name+' say '+text); 20 | } 21 | }; 22 | var tomSay = say('tom'); 23 | 24 | tomSay ('hello'); -------------------------------------------------------------------------------- /chapter08/ch08.fs_fstatSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_fstatSync.js 5 | */ 6 | console.info("------ fs fstatSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var fd = fs.openSync('txt/fstatSync.txt', 'r'); // TODO: 打开文件(同步方式) 10 | var fstatSync = fs.fstatSync(fd); // TODO: 获取文件信息(同步方法) 11 | console.info('txt/fstatSync.txt file info: '); 12 | console.info(fstatSync); // TODO: 打印输出文件信息 13 | console.info(); 14 | console.info('fs.fstatSync() Done.'); 15 | fs.closeSync(fd); 16 | console.info(); -------------------------------------------------------------------------------- /chapter08/ch08.fs_realpathSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-24. 3 | * 4 | * ch08.fs_realpathSync.js 5 | */ 6 | console.info("------ fs realpathSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var cache = {'/king':'/home/king'}; // TODO: 定义cache 10 | var relpath = 'txt/realpathSync.txt'; // TODO: 定义相对路径 11 | var resolvedPath = fs.realpathSync(relpath, cache); // TODO: 相对路径转绝对路径(同步方法) 12 | console.info('txt/realpathSync.txt realpath is : '); 13 | console.info(resolvedPath); // TODO: 打印输出绝对路径 14 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_readableA.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-3. 3 | * 4 | * ch11.stream_readable_readableA.js 5 | */ 6 | console.info("------ stream readable event ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var rs = fs.createReadStream('data/createReadStream.txt'); 13 | /** 14 | * 流(Stream)模块 --- 'readable'事件处理函数 15 | */ 16 | rs.on('readable', function() { 17 | console.log('readable event emitted.'); 18 | console.info(); 19 | }); -------------------------------------------------------------------------------- /Chapter12/express-login/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 |

<%= title %>

9 |

Welcome to <%= title %>

10 |
11 |

User id:

12 |

Password:

13 | 14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter13/ch13.util_isRegExp.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_isRegExp.js 5 | */ 6 | console.info("------ util isRegExp() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * return value is true 11 | */ 12 | console.log(util.inspect(util.isRegExp(/some regexp/))); 13 | /** 14 | * return value is true 15 | */ 16 | console.log(util.inspect(util.isRegExp(new RegExp('another regexp')))); 17 | /** 18 | * return value is false 19 | */ 20 | console.log(util.inspect(util.isRegExp({}))); -------------------------------------------------------------------------------- /chapter01/ch01.console-write.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/16. 3 | * 4 | * ch01.console-write.js 5 | */ 6 | console.info('Node.js - readline.write() Usage'); 7 | var readline = require('readline'); 8 | var rl = readline.createInterface({ 9 | input: process.stdin, 10 | output: process.stdout 11 | }); 12 | rl.write('Delete me! Wait for 3 seconds...'); 13 | var timeoutLength = 5 * 1000; // three second 14 | var timeout = setTimeout(function() { 15 | // 模仿 ctrl+u快捷键,删除之前所写行 16 | rl.write(null, {ctrl:true, name:'u'}); 17 | }, timeoutLength); 18 | // clearTimeout(timeout); -------------------------------------------------------------------------------- /chapter03/ch03.syn-asyn.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-11. 3 | * 4 | * ch03.syn-asyn.js 5 | */ 6 | function sleep(milliSeconds) { 7 | var startTime = new Date().getTime(); 8 | while (new Date().getTime() < startTime + milliSeconds); 9 | }; 10 | function synAsyn() { 11 | for (var i=0; i<5; i++) 12 | { 13 | console.info("before FOR: " + new Date()); 14 | setTimeout(function(){ 15 | console.info("in FOR: " + new Date()); 16 | }, 3000); //睡眠2秒,然后再进行一下次for循环打印 17 | console.info("after FOR: " + new Date()); 18 | } 19 | } 20 | synAsyn(); -------------------------------------------------------------------------------- /Chapter13/ch13.util_inspect.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_inspect.js 5 | */ 6 | console.info("------ util inspect() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * 定义原型类 Person 11 | * @constructor 12 | */ 13 | function Person() { 14 | this.name = 'person'; 15 | this.toString = function() { 16 | return this.name; 17 | }; 18 | } 19 | /** 20 | * 定义 Person 对象 21 | * @type {Base} 22 | */ 23 | var obj = new Person(); 24 | console.log(util.inspect(obj)); 25 | console.log(util.inspect(obj, true)); -------------------------------------------------------------------------------- /chapter01/ch01.console-trace.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/7. 3 | * 4 | * ch01.console-trace.js 5 | */ 6 | console.trace(); 7 | console.trace("start"); 8 | var fs = require('fs'); 9 | var file = 'chapter01/not-found.txt'; 10 | var encoding = 'UTF-8'; 11 | fs.readFile(file, encoding, function(err, data) { 12 | console.trace("fs-start"); 13 | if(err) { 14 | // console.error("error - \n %s", err); 15 | // console.warn("warn - \n %s", err); 16 | } else { 17 | // console.log(data); 18 | } 19 | console.trace("fs-end"); 20 | }); 21 | console.trace("end"); -------------------------------------------------------------------------------- /Chapter13/ch13.util_isError.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-24. 3 | * 4 | * ch13.util_isError.js 5 | */ 6 | console.info("------ util isError() ------"); 7 | console.info(); 8 | var util = require('util'); // TODO: 引入常用工具(Util)模块 9 | /** 10 | * return value is true 11 | */ 12 | console.log(util.inspect(util.isError(new Error()))); 13 | /** 14 | * return value is true 15 | */ 16 | console.log(util.inspect(util.isError(new TypeError()))); 17 | /** 18 | * return value is false 19 | */ 20 | console.log(util.inspect(util.isError({ 21 | name: 'Error', 22 | message: 'an error occurred' 23 | }))); -------------------------------------------------------------------------------- /chapter01/ch01.console-readline.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/16. 3 | * 4 | * ch01.console-readline.js 5 | */ 6 | var readline = require('readline'); 7 | var rl = readline.createInterface({ 8 | input: process.stdin, 9 | output: process.stdout 10 | }); 11 | rl.question("What is your name? ", function(answer) { 12 | // TODO: Log the answer in a database 13 | console.log("My name is ", answer); 14 | rl.close(); 15 | }); 16 | rl.question("How old are you? ", function(answer) { 17 | // TODO: Log the answer in a database 18 | console.log("I'm ", answer); 19 | rl.close(); 20 | }); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_exec_usage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-3. 3 | * 4 | * ch06.child_process_exec_usage.js 5 | */ 6 | console.info("------ child_process exec usage ------"); 7 | console.info(); 8 | /** 9 | * child_process exec 10 | * @type {exports.exec|*} 11 | */ 12 | var exec = require('child_process').exec; // TODO: 引入child_process模块 13 | var child = exec('cat ch06.child_process_exec_usage.js', 14 | function (error, stdout, stderr) { 15 | console.info('cat ch06.child_process_exec_usage.js stdout: '); 16 | console.log(stdout); // TODO: 打印输出 stdout 17 | }); -------------------------------------------------------------------------------- /chapter08/ch08.fs_stat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_stat.js 5 | */ 6 | console.info("------ fs stat() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 获取文件信息(异步方法) 11 | */ 12 | fs.stat('txt/stat.txt', function (err, stats) { 13 | if (err) { 14 | throw err; 15 | } else { 16 | console.info('txt/stat.txt file info: '); 17 | console.info(stats); // TODO: 打印输出文件信息 18 | console.info(); 19 | console.info('fs.stat() Done.'); 20 | console.info(); 21 | } 22 | }); 23 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_pipe.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-5. 3 | * 4 | * ch11.stream_readable_pipe.js 5 | */ 6 | console.info("------ stream pipe write file ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var readable = fs.createReadStream('data/srcFile.txt'); 13 | /** 14 | * 调用文件系统(fs)模块的createWriteStream()方法创建可写(Writable)流 15 | */ 16 | var writable = fs.createWriteStream('data/destFile.txt'); 17 | /** 18 | * 所有来自readable的数据会被写入到'data/destFile.txt'文本文件中 19 | */ 20 | readable.pipe(writable); -------------------------------------------------------------------------------- /chapter05/ch05.process-stderr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-stderr.js 5 | */ 6 | console.info("------ Process stderr ------"); 7 | console.info(); 8 | var fs = require('fs'); 9 | var file = 'err.txt'; 10 | var encoding = 'UTF-8'; 11 | fs.readFile(file, encoding, function(err, data) { 12 | if(err) { 13 | setTimeout(function() { 14 | process.stderr.write('err: ' + err + '\n'); // TODO: 打印输出标准错误流 15 | }, 1000); 16 | } else { 17 | console.log(data); 18 | } 19 | }); 20 | console.info(); 21 | console.info("------ Process stderr ------"); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_usage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-3. 3 | * 4 | * ch06.child_process_spawn_usage.js 5 | */ 6 | console.info("------ child_process spawn usage ------"); 7 | console.info(); 8 | /** 9 | * child_process spawn 10 | * @type {exports.spawn|*} 11 | */ 12 | var spawn = require('child_process').spawn; // TODO: 引入child_process模块 13 | var ls_var = spawn('ls', ['-lh', '/var']); // TODO: 定义命令行‘ls -lh /var’ 14 | /** 15 | * 捕获控制台输出对象stdout,输出捕获数据 16 | */ 17 | ls_var.stdout.on('data', function (data) { 18 | console.log('stdout: ' + data); // TODO: 打印输出 /var 目录清单 19 | }); 20 | -------------------------------------------------------------------------------- /chapter07/ch07.os_mem.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_mem.js 5 | */ 6 | console.info("------ OS mem() ------"); 7 | console.info(); 8 | var os = require('os'); // TODO: 引入OS模块 9 | var totalmem = os.totalmem(); 10 | console.info('操作系统内存总量为: ' + totalmem + ' byte.'); 11 | console.info('操作系统内存总量为: ' + parseInt(totalmem / 1024 / 1024) + ' Mb.'); 12 | console.info(); 13 | var freemem = os.freemem(); 14 | console.info('操作系统空闲内存为: ' + freemem + ' byte.'); 15 | console.info('操作系统空闲内存为: ' + parseInt(freemem / 1024 / 1024) + ' Mb.'); 16 | console.info(); 17 | console.info("------ OS mem() ------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_realpath.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-24. 3 | * 4 | * ch08.fs_realpath.js 5 | */ 6 | console.info("------ fs realpath() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var cache = {'/king':'/home/king'}; // TODO: 定义cache 10 | var relpath = 'txt/realpath.txt'; // TODO: 定义相对路径 11 | /** 12 | * 相对路径转绝对路径(异步方法) 13 | */ 14 | fs.realpath(relpath, cache, function (err, resolvedPath) { 15 | if (err) { 16 | throw err; 17 | } 18 | console.info('txt/realpath.txt realpath is : '); 19 | console.info(resolvedPath); // TODO: 打印输出绝对路径 20 | }); 21 | console.info(); -------------------------------------------------------------------------------- /chapter01/ch01.console-fibonacci.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/2. 3 | * 4 | * ch01.console-fibonacci.js 5 | */ 6 | console.info("\n"); 7 | console.info("------Fibonacci数列应用------"); 8 | console.info("\n"); 9 | var strFibonacci; // 定义字符串变量,用于输出Fibonacci数列 10 | var i=1, j=1, s=i+j; // 初始化变量i,j 11 | strFibonacci = "输出Fibonacci数列>>> 1 1 "; // 初始化Fibonacci数列 12 | // 循环结束判断条件 13 | while(s <= 1000) 14 | { 15 | strFibonacci = strFibonacci + s + " "; 16 | i = j; 17 | j = s; 18 | s = i + j; // Fibonacci 数列:F(n) = F(n-1) + F(n-2) 19 | } 20 | console.info(strFibonacci); // 打印输出Fibonacci数列 21 | console.info("\n"); -------------------------------------------------------------------------------- /chapter05/ch05.process-stdout.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-stdout.js 5 | */ 6 | console.info("------ Process stdout ------"); 7 | console.info(); 8 | console.log('Node.js Process Module - stdout method.'); 9 | process.stdout.write('Node.js Process Module - stdout method.'); 10 | console.info('\n'); 11 | console.info('console.log()方法封装了process.stdout.write()方法'); 12 | console.log = function(d){ 13 | process.stdout.write('process.stdout.write: ' + d + '\n'); 14 | } 15 | console.log('Node.js Process Module - stdout method.'); 16 | console.info(); 17 | console.info("------ Process stdout ------"); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_exec_last.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_exec_last.js 5 | */ 6 | console.info("------ child_process exec last ------"); 7 | console.info(); 8 | /** 9 | * 创建子进程统计系统登录次数 10 | * @type {exports.exec|*} 11 | */ 12 | var exec = require('child_process').exec; 13 | var last = exec('last | wc -l'); 14 | /** 15 | * 捕获控制台输出对象stdout的‘data’事件 16 | */ 17 | last.stdout.on('data', function (data) { 18 | console.log('系统登录次数统计: ' + data); 19 | }); 20 | /** 21 | * 绑定系统‘exit’事件 22 | */ 23 | last.on('exit', function (code) { 24 | console.log('子进程已关闭,代码: ' + code); 25 | }); -------------------------------------------------------------------------------- /chapter09/ch09.path_dirname.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-11. 3 | * 4 | * ch09.path_dirname.js 5 | */ 6 | console.info("------ path dirname() ------"); 7 | console.info(); 8 | var path = require('path'); // TODO: 引入路径处理模块 9 | /** 10 | * 测试 path.dirname() 函数方法 11 | * @type {string} 12 | */ 13 | var path_a = "test"; 14 | var path_b = "test.txt"; 15 | var path_resolve = path.resolve(path_a, path_b); 16 | console.info('path.resolve("test","test.txt") is : '); 17 | console.info(path_resolve); 18 | console.info(); 19 | console.info("The file test.txt's dirname is : "); 20 | console.info(path.dirname(path_resolve)); 21 | console.info(); -------------------------------------------------------------------------------- /chapter09/ch09.path_extname.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-11. 3 | * 4 | * ch09.path_extname.js 5 | */ 6 | console.info("------ path extname() ------"); 7 | console.info(); 8 | var path = require('path'); // TODO: 引入路径处理模块 9 | /** 10 | * 测试 path.extname() 函数方法 11 | * @type {string} 12 | */ 13 | var path_a = "test"; 14 | var path_b = "test.txt"; 15 | var path_resolve = path.resolve(path_a, path_b); 16 | console.info('path.resolve("test","test.txt") is : '); 17 | console.info(path_resolve); 18 | console.info(); 19 | console.info('path.extname("test.txt") is : '); 20 | console.info(path.extname(path_resolve)); 21 | console.info(); -------------------------------------------------------------------------------- /chapter02/ch02.module-counter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | */ 4 | var outputVal = 0; //输出值 5 | var increment = 1; //增量 6 | /* 设置输出值 */ 7 | function seOutputVal (val) { 8 | outputVal = val; 9 | } 10 | /* 设置增量 */ 11 | function setIncrement(incrementVal){ 12 | increment = incrementVal; 13 | } 14 | /* 输出 */ 15 | function printNextCount() 16 | { 17 | outputVal += increment; 18 | console.log(outputVal) ; 19 | } 20 | function printOutputVal() { 21 | console.log(outputVal); 22 | } 23 | exports.seOutputVal = seOutputVal; 24 | exports.setIncrement = setIncrement; 25 | module.exports.printNextCount = printNextCount; -------------------------------------------------------------------------------- /chapter05/ch05.process-kill.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-23. 3 | * 4 | * ch05.process-kill.js 5 | */ 6 | console.info("------ Process kill pid ------"); 7 | console.info(); 8 | console.info('当前进程id:' + process.pid); 9 | console.info(); 10 | process.on('SIGHUP', function() { 11 | console.log('Got SIGHUP signal.'); 12 | }); 13 | setTimeout(function() { 14 | console.log('Exiting...'); 15 | process.exit(0); 16 | console.info('已经退出进程id:' + process.pid); 17 | }, 1000); 18 | process.kill(process.pid, 'SIGHUP'); 19 | console.info('正在退出进程id:' + process.pid); 20 | console.info(); 21 | console.info("------ Process kill pid ------"); -------------------------------------------------------------------------------- /chapter09/ch09.path_join.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-8. 3 | * 4 | * ch09.path_join.js 5 | */ 6 | console.info("------ path join() ------"); 7 | console.info(); 8 | var path = require('path'); // TODO: 引入路径处理模块 9 | /** 10 | * 测试 path.join() 函数方法 11 | * @type {string} 12 | */ 13 | var path_a = "home"; 14 | var path_b = "king"; 15 | var path_c = "webstorm.js"; 16 | console.info('path.join("home","king","webstorm.js") is : ' + path.join(path_a, path_b, path_c)); 17 | console.info(); 18 | var path_d = "home"; 19 | var path_e = "king"; 20 | console.info('path.join("home",{},"king") is : ' + path.join(path_d, {}, path_e)); 21 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_writable_file.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-9. 3 | * 4 | * ch11.stream_writable_file.js 5 | */ 6 | console.info("------ stream writable file ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)createWriteStream()方法创建可写(Writable)流 11 | */ 12 | var ws = fs.createWriteStream('data/writable.txt'); 13 | ws.write('stream - '); // TODO: 写数据 14 | ws.write('writable - '); // TODO: 写数据 15 | ws.write('file - '); // TODO: 写数据 16 | /** 17 | * 通过setTimeout()方法设置1000ms时间延迟 18 | * 自行关闭文件流 19 | */ 20 | setTimeout(function () { 21 | ws.end('end.\n'); // TODO: 关闭文件流 22 | }, 1000); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readlinkSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-23. 3 | * 4 | * ch08.fs_readlinkSync.js 5 | */ 6 | console.info("------ fs readlinkSync() ------"); 7 | console.info(); 8 | var srcpath = "txt/symlinkSync.txt"; 9 | var linkpath = "txtlink/symlinkSync.txt"; 10 | var fs = require('fs'); // TODO: 引入文件系统模块 11 | var linkString = fs.readlinkSync(linkpath); // TODO: 读取链接文件(同步方式) 12 | console.info('read linkpath: ' + linkString); 13 | console.log('fs.readlinkSync() Done.'); 14 | var srcpath = fs.readlinkSync(srcpath); // TODO: 读取链接文件(同步方式) 15 | console.info('read srcpath: ' + srcpath); 16 | console.log('fs.readlinkSync() Done.'); 17 | console.info(); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_fork_main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_fork_main.js 5 | */ 6 | console.info("------ child_process fork main ------"); 7 | console.info(); 8 | /** 9 | * child_process fork 10 | * @type {exports} 11 | */ 12 | var cp = require('child_process'); // TODO: 引入child_process模块 13 | var n = cp.fork('ch06.child_process_fork_sub.js'); // TODO: fork 子进程 14 | /** 15 | * fork message event 16 | */ 17 | n.on('message', function(m) { 18 | console.log('PARENT got message:', m); 19 | }); 20 | /** 21 | * child_process send message 22 | */ 23 | n.send({ main: 'sub' }); // TODO: send message 24 | console.info(); -------------------------------------------------------------------------------- /chapter10/ServerListening/ch10.net_listening.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_listening.js 5 | */ 6 | console.info("------ net listening() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 7788; // TODO: 定义端口号 11 | /** 12 | * 创建TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听"listening"事件 17 | */ 18 | server.on('listening', function() { 19 | console.log('Server is listening on port ', PORT); 20 | console.info(); 21 | }); 22 | /** 23 | * 调用server.listen()监听服务器端口 24 | */ 25 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_pipe_push.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-4. 3 | * 4 | * ch11.stream_readable_pipe_push.js 5 | */ 6 | console.info("------ stream readable pipe push ------"); 7 | console.info(); 8 | var stream = require('stream'); // TODO: 引入流(Stream)模块 9 | var rs = new stream.Readable; // TODO: 定义Readable对象 10 | rs.push('Stream '); // TODO: 使用push()方法发送数据 11 | rs.push('Readable '); // TODO: 使用push()方法发送数据 12 | rs.push('Push() '); // TODO: 使用push()方法发送数据 13 | rs.push('Pipe() '); // TODO: 使用push()方法发送数据 14 | rs.push('\n'); // TODO: 使用push()方法发送数据 15 | rs.push(null); // TODO: 使用push()方法通知发送数据完毕 16 | rs.pipe(process.stdout); // TODO: 使用pipe()方法导出数据 -------------------------------------------------------------------------------- /chapter04/ch04.buffer-toJSON.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-toJSON.js 5 | */ 6 | console.info("------ Buffer toJSON ------"); 7 | console.info(); 8 | var buf = new Buffer('test'); 9 | var json = JSON.stringify(buf); 10 | console.log(json); 11 | /** 12 | * { 13 | * "type":"Buffer", 14 | * "data":[116,101,115,116] 15 | * } 16 | */ 17 | var copy = JSON.parse(json, function(key, value) { 18 | return value && value.type === 'Buffer' 19 | ? new Buffer(value.data) 20 | : value; 21 | }); 22 | console.log(copy); 23 | // 24 | console.info(); 25 | console.info("------ Buffer toJSON ------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readdir.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-28. 3 | * 4 | * ch08.fs_readdir.js 5 | */ 6 | console.info("------ fs readdir() ------"); 7 | console.info(); 8 | var path = "txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | /** 11 | * 读取文件目录(异步方式) 12 | */ 13 | fs.readdir(path, function (err, files) { 14 | if (err) { 15 | // throw err; 16 | console.info('err: ' + err); 17 | console.info(); 18 | } else { 19 | console.info('read directory txt: '); 20 | console.info(files); // TODO: 打印输出文件目录 21 | console.log('fs.readdir() Done.'); 22 | console.info(); 23 | } 24 | }); 25 | console.info(); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readFileSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-28. 3 | * 4 | * ch08.fs_readFileSync.js 5 | */ 6 | console.info("------ fs readFileSync() ------"); 7 | console.info(); 8 | var file_path = "txt/readFileSync.txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | if(fs.existsSync(file_path)) { 11 | var file_contents = fs.readFileSync(file_path, 'utf-8'); // TODO: 读文件(同步方式) 12 | console.info('read txt/readFileSync.txt contents: '); 13 | console.info(file_contents); // TODO: 打印输出文件内容 14 | console.info(); 15 | } else { 16 | console.log(file_path + 'is not exists.'); 17 | console.info(); 18 | } 19 | console.log('fs.readfileSync() Done.'); 20 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-3. 3 | * 4 | * ch11.stream_readable_error.js 5 | */ 6 | console.info("------ stream error event ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var rs = fs.createReadStream('data/error.txt'); 13 | /** 14 | * 流(Stream)模块 --- 'readable'事件处理函数 15 | */ 16 | rs.on('readable', function() { 17 | console.log('readable event emitted.'); 18 | console.info(); 19 | }); 20 | /** 21 | * 流(Stream)模块 --- 'error'事件处理函数 22 | */ 23 | rs.on('error', function () { 24 | console.log('error event emitted.'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /Chapter11/data/fs_readFileSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-28. 3 | * 4 | * ch08.fs_readFileSync.js 5 | */ 6 | console.info("------ fs readFileSync() ------"); 7 | console.info(); 8 | var file_path = "writable.txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | if(fs.existsSync(file_path)) { 11 | var file_contents = fs.readFileSync(file_path, 'utf-8'); // TODO: 读文件(同步方式) 12 | console.info('read writable.txt contents: '); 13 | console.info(); 14 | console.info(file_contents); // TODO: 打印输出文件内容 15 | console.info(); 16 | } else { 17 | console.log(file_path + 'is not exists.'); 18 | console.info(); 19 | } 20 | console.log('fs.readfileSync() Done.'); 21 | console.info(); -------------------------------------------------------------------------------- /chapter03/ch03.async-series-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-23. 3 | * 4 | * ch03.asyn-series-array.js 5 | */ 6 | console.info('------ Node.js异步编程: Async series ------'); 7 | console.info(); 8 | var async = require('async'); // TODO: 引用'async'包 9 | /** 10 | * TODO: 使用series函数方法 11 | */ 12 | async.series([ 13 | function(callback) { 14 | callback(null, 'hello'); 15 | }, 16 | function(callback) { 17 | callback(null, 'async'); 18 | }, 19 | function(callback) { 20 | callback(null, 'series'); 21 | } 22 | ],function(err, results) { 23 | console.log(results); 24 | }); 25 | console.info(); 26 | console.info('------ Node.js异步编程: Async series ------'); -------------------------------------------------------------------------------- /chapter10/ServerClose/ch10.net_close_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-21. 3 | * 4 | * ch10.net_close_client.js 5 | */ 6 | console.info("------ net close() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.end(); 18 | }); 19 | /** 20 | * 为TCP客户端实例添加一个"end"事件处理函数 21 | */ 22 | client.on('end', function() { 23 | console.log('client disconnected'); 24 | console.info(); 25 | }); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_fork_usage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-7. 3 | * 4 | * ch06.child_process_fork_usage.js 5 | */ 6 | console.info("------ child_process fork usage ------"); 7 | console.info(); 8 | /** 9 | * child_process fork 10 | * @type {exports.fork} 11 | */ 12 | var fork = require('child_process').fork; // TODO: 引入child_process模块 13 | /** 14 | * 获取当前机器的 CPU 内核数量 15 | */ 16 | var cpus = require('os').cpus(); 17 | console.info('当前机器CPU内核数量: ' + cpus.length); // TODO: 获取 CPU 内核数量 18 | for (var i = 0; i < cpus.length; i++) { 19 | /** 20 | * 通过fork()方法创建新的子进程 21 | */ 22 | console.log('Fork a new child_process now...'); 23 | fork('./worker.js'); // TODO: 生成新子进程 24 | } -------------------------------------------------------------------------------- /chapter03/ch03.async-compose.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-compose.js 5 | */ 6 | var async = require('async'); 7 | function fn1(n, callback) { 8 | setTimeout(function () { 9 | callback(null, n + 1); 10 | }, 1000); 11 | } 12 | function fn2(n, callback) { 13 | setTimeout(function () { 14 | callback(null, n * 3); 15 | }, 1000); 16 | } 17 | var demo = async.compose(fn1, fn2); 18 | demo(4, function (err, result) { 19 | // result now equals 15 20 | }); 21 | //compose(fn1, fn2...); 22 | //创建一个包括一组异步函数的函数集合,每个函数会消费上一次函数的返回值。把f(),g(),h()异步函数,组合成f(g(h()))的形式,通过callback得到返回值。 23 | //执行示例代码,将result结果输出到控制台,观察运行消耗的时间。 24 | //compose和waterfall作用相仿,不过compose更加灵活,可以自定义传入参数。 -------------------------------------------------------------------------------- /chapter03/ch03.async-series-json.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-23. 3 | * 4 | * ch03.asyn-series-json.js 5 | */ 6 | console.info('------ Node.js异步编程: Async series ------'); 7 | console.info(); 8 | var async = require('async'); // TODO: 引用'async'包 9 | /** 10 | * TODO: 使用series函数方法 11 | */ 12 | async.series({ 13 | one: function(callback) { 14 | callback(null, 'hello'); 15 | }, 16 | two: function(callback) { 17 | callback(null, 'async'); 18 | }, 19 | three: function(callback) { 20 | callback(null, 'series'); 21 | } 22 | },function(err, results) { 23 | console.log(results); 24 | }); 25 | console.info(); 26 | console.info('------ Node.js异步编程: Async series ------'); -------------------------------------------------------------------------------- /chapter02/ch02.module-counter-obj.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-counter-obj.js 5 | */ 6 | var outputVal = 0; //输出值 7 | var increment = 1; //增量 8 | /** 9 | * 设置输出值 10 | */ 11 | exports.seOutputVal = function(val) { 12 | outputVal = val; 13 | } 14 | /** 15 | * 设置增量值 16 | */ 17 | exports.setIncrement = function(incrementVal) { 18 | increment = incrementVal; 19 | } 20 | /** 21 | * 增量打印输出 22 | */ 23 | exports.printNextCount = function() { 24 | outputVal += increment; 25 | console.log(outputVal) ; 26 | } 27 | /** 28 | * 自动清零 29 | */ 30 | exports.autoSetZero = function() { 31 | if(outputVal >= 100) { 32 | outputVal = 0; 33 | } 34 | console.log(outputVal); 35 | } -------------------------------------------------------------------------------- /chapter10/SocketAddress/ch10.net_socketaddr_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketaddr_client.js 5 | */ 6 | console.info("------ net socket.address() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 6677; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.end(); 18 | }); 19 | /** 20 | * 为TCP客户端实例添加一个"end"事件处理函数 21 | */ 22 | client.on('end', function() { 23 | console.log('client disconnected'); 24 | console.info(); 25 | }); -------------------------------------------------------------------------------- /chapter02/ch02.module-file-foo.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-file-foo.js 5 | */ 6 | var circle = require('./ch02.module-file-circle.js'); 7 | console.info(); 8 | var readline = require('readline'); 9 | var rl = readline.createInterface({ 10 | input: process.stdin, 11 | output: process.stdout 12 | }); 13 | rl.question("Please input radius:\t", function(answer) { 14 | // TODO: print user input 15 | console.log("The radius is:\t", answer); 16 | console.log( 'The area of a circle of radius ' + answer + ' is ' + circle.area(answer)); 17 | console.log( 'The circumference of a circle of radius ' + answer + ' is ' + circle.circumference(answer)); 18 | console.info(); 19 | rl.close(); 20 | }); -------------------------------------------------------------------------------- /chapter10/SocketRemoteAddress/ch10.net_remoteaddr_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_remoteaddr_client.js 5 | */ 6 | console.info("------ net socket.remoteaddress() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 6677; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.end(); 18 | }); 19 | /** 20 | * 为TCP客户端实例添加一个"end"事件处理函数 21 | */ 22 | client.on('end', function() { 23 | console.log('client disconnected'); 24 | console.info(); 25 | }); -------------------------------------------------------------------------------- /chapter09/ch09.path_resolve.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-9. 3 | * 4 | * ch09.path_resolve.js 5 | */ 6 | console.info("------ path resolve() ------"); 7 | console.info(); 8 | var path = require('path'); // TODO: 引入路径处理模块 9 | /** 10 | * 测试 path.resolve() 函数方法 11 | * @type {string} 12 | */ 13 | console.info("Current working directory : "); 14 | console.info(process.cwd()); 15 | console.info(); 16 | var path_a = "ch09.path_resolve.js"; 17 | console.info('path.resolve("ch09.path_resolve.js") is : '); 18 | console.info(path.resolve(path_a)); 19 | console.info(); 20 | var path_b = "test"; 21 | var path_c = "test.txt"; 22 | console.info('path.resolve("test","test.txt") is : '); 23 | console.info(path.resolve(path_b, path_c)); 24 | console.info(); -------------------------------------------------------------------------------- /chapter10/connection/ch10.net_connection.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-19. 3 | * 4 | * ch10.net_connection.js 5 | */ 6 | console.info("------ net connection() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 9696; // TODO: 定义端口号 11 | /** 12 | * 创建 TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听端口和主机 17 | */ 18 | server.listen(PORT, HOST); 19 | console.log('Server listening on ' + server.address()); 20 | console.info(); 21 | /** 22 | * 通过显式调用"connection"事件建立TCP连接 23 | */ 24 | server.on('connection', function(sock) { 25 | console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort); 26 | }); -------------------------------------------------------------------------------- /Chapter12/express-helloworld/views/index.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= title %> 5 | 6 | 7 | 8 | 9 |
10 |

<%= title %>

11 |

Hello World, this is a simple Express Page with Bootstrap.

12 |

About Express

13 |
14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter04/ch04.buffer.concat/lib/parse-header-string.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/17. 3 | * 4 | * parse-header-string.js 5 | */ 6 | /** 7 | * exports parse function 8 | * @param data 9 | * @returns {*} 10 | */ 11 | exports.parse = function parse(data) { 12 | var lines = data.toString('ascii').split("\n"); 13 | var cut, name, host; 14 | for (var i=0, len=lines.length; i < len; i++) { 15 | cut = lines[i].split(':'); 16 | name = cut[0]; 17 | if (name === 'Host') { 18 | if (cut[1] === undefined) { 19 | return 'Host header not found'; 20 | } 21 | host = cut[1].trim().toLowerCase(); 22 | return host; 23 | } 24 | } 25 | return null; 26 | }; -------------------------------------------------------------------------------- /chapter05/ch05.process-stdin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-stdin.js 5 | */ 6 | console.info("------ Process stdin ------"); 7 | console.info(); 8 | console.info('用户输入数据'); 9 | /** 10 | * readable - 接受控制台用户输入事件 11 | */ 12 | process.stdin.setEncoding('utf8'); 13 | process.stdin.on('readable', function() { 14 | var chunk = process.stdin.read(); // TODO: process.stdin.read() 方法 15 | if (chunk !== null) { 16 | process.stdout.write('Print Data: ' + chunk + '\n'); // TODO: 打印输出 17 | } 18 | }); 19 | /** 20 | * end - 结束控制台输入事件 21 | */ 22 | process.stdin.on('end', function() { 23 | process.stdout.write('end.\n'); 24 | }); 25 | console.info(); 26 | console.info("------ Process stdin ------"); -------------------------------------------------------------------------------- /chapter03/ch03.async-parallel.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-parallel.js 5 | */ 6 | console.info('------ Node.js异步编程: Async parallel ------'); 7 | console.info(); 8 | var async = require('async'); // TODO: 引用'async'包 9 | /** 10 | * TODO: 使用parallel函数方法 11 | */ 12 | async.parallel([ 13 | function(callback) { 14 | setTimeout(function() { 15 | callback(null, 'one'); 16 | }, 2000); 17 | }, 18 | function(callback) { 19 | setTimeout(function() { 20 | callback(null, 'two'); 21 | }, 1000); 22 | } 23 | ], 24 | function(err, results) { 25 | console.log(results); 26 | }); 27 | console.info(); 28 | console.info('------ Node.js异步编程: Async parallel ------'); -------------------------------------------------------------------------------- /chapter04/ch04.buffer-definesize.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-definesize.js 5 | */ 6 | // TODO: 定义并初始化Buffer对象 --- buffer 7 | var buffer = new Buffer("This is Buffer", "utf8"); // TODO: 初始化 buffer 8 | console.log("The variable buffer's length is " + buffer.length); 9 | console.log("The variable buffer is " + buffer); 10 | // TODO: 定义并初始化Buffer对象 --- buffer16 11 | var buffer16 = new Buffer(16); 12 | console.log("The variable buffer16's length is " + buffer16.length); 13 | console.log("The variable buffer16 is " + buffer16); 14 | buffer16.write("This is Buffer", 0, "utf8"); // TODO: 初始化 buffer16 15 | console.log("The variable buffer16's length is " + buffer16.length); 16 | console.log("The variable buffer16 is " + buffer16); -------------------------------------------------------------------------------- /chapter04/ch04.buffer-isBuffer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-isBuffer.js 5 | */ 6 | console.info("------Buffer.isBuffer()------"); 7 | console.info(); 8 | var buffer = new Buffer('nodejs', 'utf8'); // TODO: 编码形式 9 | // TODO: 判断是否为Buffer对象 10 | if(Buffer.isBuffer(buffer)) 11 | { 12 | console.info("The 'buffer' is a Buffer obj."); 13 | } 14 | else 15 | { 16 | console.info("The 'buffer' is not a Buffer obj."); 17 | } 18 | var str = "nodejs"; // TODO: 定义字符串变量 19 | // TODO: 判断是否为Buffer对象 20 | if(Buffer.isBuffer(str)) 21 | { 22 | console.info("The 'str' is a Buffer obj."); 23 | } 24 | else 25 | { 26 | console.info("The 'str' is not a Buffer obj."); 27 | } 28 | console.info(); 29 | console.info("------Buffer.isBuffer()------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_fstat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_fstat.js 5 | */ 6 | console.info("------ fs fstat() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | fs.open('txt/fstat.txt', 'r', function (err, fd) { 10 | if (err) { 11 | throw err; 12 | } 13 | /** 14 | * 获取文件信息(异步方法) 15 | */ 16 | fs.fstat(fd, function (err, stats) { 17 | if (err) { 18 | throw err; 19 | } else { 20 | console.info('txt/fstat.txt file info: '); 21 | console.info(stats); // TODO: 打印输出文件信息 22 | console.info(); 23 | console.info('fs.fstat() Done.'); 24 | console.info(); 25 | } 26 | }); 27 | }); 28 | console.info(); -------------------------------------------------------------------------------- /Chapter12/createserver/ch12.http_createServer_basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_createServer_basic.js 5 | */ 6 | console.info("------ http - create basic server ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 调用http.createServer()函数方法创建服务器 11 | */ 12 | http.createServer(function(req, res) { 13 | /** 14 | * 通过res.writeHead()函数方法写HTTP文件头 15 | */ 16 | res.writeHead(200, {'Content-type' : 'text/html'}); 17 | /** 18 | * 通过res.write()函数方法写页面内容 19 | */ 20 | res.write('

Node.js --- HTTP

'); 21 | /** 22 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 23 | */ 24 | res.end('

Create Basic HTTP Server!

'); 25 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter03/ch03.closure-bak.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-11. 3 | * 4 | * ch03.closure-bak.js 5 | */ 6 | function f1() { 7 | var n=999; 8 | nAdd=function() { 9 | n+=1; 10 | } 11 | function f2() { 12 | alert(n); 13 | } 14 | return f2; 15 | } 16 | var result=f1(); 17 | result(); // 999 18 | nAdd(); 19 | result(); // 1000 20 | 21 | /*在这段代码中,result实际上就是闭包f2函数。它一共运行了两次,第一次的值是999,第二次的值是1000。这证明了,函数f1中的局部变量n一直保存在内存中,并没有在f1调用后被自动清除。 22 | 为什么会这样呢?原因就在于f1是f2的父函数,而f2被赋给了一个全局变量,这导致f2始终在内存中,而f2的存在依赖于f1,因此f1也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。 23 | 这段代码中另一个值得注意的地方,就是“nAdd=function(){n+=1}”这一行,首先在nAdd前面没有使用var关键字,因此 nAdd是一个全局变量,而不是局部变量。其次,nAdd的值是一个匿名函数(anonymous function),而这个 24 | 匿名函数本身也是一个闭包,所以nAdd相当于是一个setter,可以在函数外部对函数内部的局部变量进行操作。*/ 25 | -------------------------------------------------------------------------------- /chapter04/ch04.buffer-slice.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/16. 3 | * 4 | * ch04.buffer-slice.js 5 | */ 6 | console.info("------ Buffer slice ------"); 7 | console.info(); 8 | /** 9 | * Create a new Buffer obj 10 | */ 11 | var buf = new Buffer(26); 12 | for(var i = 0; i < 26; i++) { 13 | buf[i] = i + 97; // TODO: 97 is ASCII 'a' 14 | } 15 | var buf_slice_a = buf.slice(0, 5); // TODO: slice buf 16 | console.log(buf_slice_a.toString('ascii', 0, buf_slice_a.length)); 17 | for(var j = 0; j < 26; j++) { 18 | buf[j] = 122 - j; // TODO: 122 is ASCII 'z' 19 | } 20 | var buf_slice_b = buf.slice(0, 5); // TODO: slice buf 21 | console.log(buf_slice_b.toString('ascii', 0, buf_slice_b.length)); 22 | console.info(); 23 | console.info("------ Buffer slice ------"); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_execFile_err.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_execFile_err.js 5 | */ 6 | console.info("------ child_process execFile error ------"); 7 | console.info(); 8 | /** 9 | * child_process execFile 10 | * 查看当前目录内容 11 | * @type {exports} 12 | */ 13 | var child_process = require('child_process'); // TODO: 引入child_process模块 14 | child_process.execFile('/bin/ls', ['-lh', '/err'], function (error,stdout,stderr) { 15 | if (error !== null) { 16 | console.log('execFile error: ' + error); // TODO: 打印输出 error 17 | console.log('execFile stderr: ' + stderr); // TODO: 打印输出 stderr 18 | } else { 19 | console.info('当前目录内容:'); 20 | console.info(stdout); // TODO: 打印输出 stdout 21 | } 22 | }); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_execFile_usage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_execFile_usage.js 5 | */ 6 | console.info("------ child_process execFile usage ------"); 7 | console.info(); 8 | /** 9 | * child_process execFile 10 | * 查看当前目录内容 11 | * @type {exports} 12 | */ 13 | var child_process = require('child_process'); // TODO: 引入child_process模块 14 | child_process.execFile('/bin/ls', ['-lh', '.'], function (error,stdout,stderr) { 15 | if (error !== null) { 16 | console.log('execFile error: ' + error); // TODO: 打印输出 error 17 | console.log('execFile stderr: ' + stderr); // TODO: 打印输出 error 18 | } else { 19 | console.info('当前目录内容:'); 20 | console.info(stdout); // TODO: 打印输出 stdout 21 | } 22 | }); -------------------------------------------------------------------------------- /chapter10/ServerConnection/ch10.net_connection_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_connection_client.js 5 | */ 6 | console.info("------ net ServerClient() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('client disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter09/ch09.url_resolve.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-13. 3 | * 4 | * ch09.url_resolve.js 5 | */ 6 | console.info("------ url parse() ------"); 7 | console.info(); 8 | var url = require('url');// TODO: 引入路径处理模块 9 | /** 10 | * 测试 url.resolve() 函数方法 11 | * @type {string} 12 | */ 13 | console.info(url.resolve('/one/two/three', 'four')); 14 | console.info(url.resolve('/one/two/three/', 'four')); 15 | console.info(url.resolve('/one/two/three', '/four')); 16 | console.info(url.resolve('/one/two/three/', '/four')); 17 | console.info(url.resolve('http://www.example.com/one', 'two')); 18 | console.info(url.resolve('http://www.example.com/one', '/two')); 19 | console.info(url.resolve('http://www.example.com/one/', 'two')); 20 | console.info(url.resolve('http://www.example.com/one/', '/two')); -------------------------------------------------------------------------------- /chapter10/ServerError/ch10.net_error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-21. 3 | * 4 | * ch10.net_error.js 5 | */ 6 | console.info("------ net error ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 创建 TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听"listening"事件 17 | */ 18 | server.on('listening', function() { 19 | console.log('Server is listening on port', PORT); 20 | console.info(); 21 | }); 22 | /** 23 | * 监听"error"事件 24 | */ 25 | server.on('error', function(err) { 26 | console.log('Error occurred:', err.message); 27 | }); 28 | /** 29 | * 调用server.listen()监听服务器端口 30 | */ 31 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /Chapter12/requestbasic/ch12.http_response_basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_response_basic.js 5 | */ 6 | console.info("------ http - create basic server ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 调用http.createServer()函数方法创建服务器 11 | */ 12 | http.createServer(function(req, res) { 13 | /** 14 | * 通过res.writeHeader()函数方法写HTTP文件头 15 | */ 16 | res.writeHead(200, {'Content-type' : 'text/html'}); 17 | /** 18 | * 通过res.write()函数方法写页面内容 19 | */ 20 | res.write('

Node.js --- HTTP

'); 21 | /** 22 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 23 | */ 24 | res.end('

Create Basic HTTP Server Response to clients request!

'); 25 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter03/ch03.async-parallelLimit.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-parallelLimit.js 5 | */ 6 | console.info('------ Node.js异步编程: Async parallelLimit ------'); 7 | console.info(); 8 | var async = require('async'); // TODO: 引用'async'包 9 | /** 10 | * TODO: 使用parallelLimit函数方法 11 | */ 12 | async.parallelLimit([ 13 | function(callback) { 14 | setTimeout(function() { 15 | callback(null, 'one'); 16 | }, 1000); 17 | }, 18 | function(callback) { 19 | setTimeout(function() { 20 | callback(null, 'two'); 21 | }, 1000); 22 | } 23 | ], 24 | 1, 25 | function(err, results) { 26 | console.log(results); 27 | }); 28 | console.info(); 29 | console.info('------ Node.js异步编程: Async parallelLimit ------'); -------------------------------------------------------------------------------- /chapter10/ServerGetConnections/ch10.net_getconnections_clientA.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_getconnections_clientA.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('clientA connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientA disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter10/ServerGetConnections/ch10.net_getconnections_clientB.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_getconnections_clientB.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client B connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientB disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter10/ServerGetConnections/ch10.net_getconnections_clientC.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_getconnections_clientC.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('clientC connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientC disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter10/ServerMaxConnections/ch10.net_maxconnections_clientA.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_maxconnections_clientA.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('clientA connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientA disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter10/ServerMaxConnections/ch10.net_maxconnections_clientB.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_maxconnections_clientB.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client B connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientB disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /chapter10/ServerMaxConnections/ch10.net_maxconnections_clientC.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_maxconnections_clientC.js 5 | */ 6 | console.info("------ net getconnections() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('clientC connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | //client.end(); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"end"事件处理函数 22 | */ 23 | client.on('end', function() { 24 | console.log('clientC disconnected'); 25 | console.info(); 26 | }); -------------------------------------------------------------------------------- /Chapter12/pingserver/ch12.http_server_ping.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_server_ping.js 5 | */ 6 | console.info("------ http - server ping ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start HTTP server..."); 10 | console.info(); 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | /** 16 | * 通过res.writeHead()函数方法写HTTP文件头 17 | */ 18 | if(Math.round(Math.random())) { 19 | res.writeHead(200, {'Content-type' : 'text/html'}); 20 | } else { 21 | res.writeHead(404, {'Content-type' : 'text/html'}); 22 | } 23 | /** 24 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 25 | */ 26 | res.end(); 27 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter06/ch06.child_process_fib_main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-10. 3 | * 4 | * ch06.child_process_fib_main.js 5 | */ 6 | console.info("------ child_process fib main ------"); 7 | console.info(); 8 | /** 9 | * child_process fork 10 | * @type {exports} 11 | */ 12 | var cp = require('child_process'); // TODO: 引入child_process模块 13 | var child = cp.fork('ch06.child_process_fib_sub.js'); // TODO: 每个请求都单独生成一个新的子进程 14 | /** 15 | * fork message event 16 | */ 17 | child.on('message', function(m) { 18 | console.info('斐波那契数列: ' + m.result + '\n'); 19 | }); 20 | /** 21 | * child_process send message 22 | */ 23 | var input = parseInt('10'); 24 | child.send({input : 1}); // TODO: send message 25 | for(var i = 1; i < input; i++) { 26 | child.send({input : i}); // TODO: send message 27 | } 28 | -------------------------------------------------------------------------------- /chapter02/ch02.module-exchangerate-load.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exchangerate-load.js 5 | */ 6 | console.info("\n"); 7 | console.info("------汇率换算应用------"); 8 | console.info("\n"); 9 | var exRate = require('./ch02.module-exchangerate.js'); // 加载自定义模块 10 | var readline = require('readline'); // 加载核心模块 11 | var rl = readline.createInterface({ 12 | input: process.stdin, 13 | output: process.stdout 14 | }); 15 | rl.question("Please enter count: ", function(iMoney) { 16 | // TODO: 调用dollar2rmb()方法将美元换算成人民币 17 | console.info(iMoney + ' US-Dollar exchange to RMB equals ' + exRate.dollar2rmb(iMoney)); 18 | // TODO: 调用rmb2dollar()方法将人民币换算成美元 19 | console.info(iMoney + ' RMB exchange to US-Dollar equals ' + exRate.rmb2dollar(iMoney)); 20 | rl.close(); 21 | }); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_std.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-3. 3 | * 4 | * ch06.child_process_spawn_std.js 5 | */ 6 | console.info("------ child_process spawn std ------"); 7 | console.info(); 8 | var cp = require('child_process'); // TODO: 引入child_process模块 9 | var cat = cp.spawn('cat'); // TODO: 定义命令行‘cat’ 10 | /** 11 | * 捕获控制台输出对象stdout的‘data’事件 12 | */ 13 | cat.stdout.on('data', function(d) { 14 | console.log(d.toString()); 15 | }); 16 | /** 17 | * 绑定系统‘exit’事件 18 | */ 19 | cat.on('exit', function() { 20 | console.log('cat on exit!'); 21 | }); 22 | /** 23 | * 绑定系统‘close’事件 24 | */ 25 | cat.on('close', function() { 26 | console.log('cat on close!'); 27 | }); 28 | cat.stdin.write('cat on data!'); // TODO: 通过控制台输入对象stdin写入数据 29 | cat.stdin.end(); // TODO: 结束控制台输入对象stdin -------------------------------------------------------------------------------- /chapter03/ch03.async-waterfall.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-waterfall.js 5 | */ 6 | console.info('------ Node.js异步编程: Async waterfall ------'); 7 | console.info(); 8 | var async = require('async'); // TODO: 引用'async'包 9 | /** 10 | * TODO: 使用waterfall函数方法 11 | */ 12 | async.waterfall([ 13 | function(callback) { 14 | callback(null, 1); // TODO: 当回调函数的第一个参数为非空值时,waterfall会停止执行剩余任务 15 | }, 16 | function(data, callback) { 17 | console.info(data); 18 | callback('test', 2); 19 | }, 20 | function(data, callback) { 21 | console.info(data); 22 | callback(null, 3); 23 | } 24 | ],function(err, results) { 25 | console.log(results); 26 | }); 27 | console.info(); 28 | console.info('------ Node.js异步编程: Async waterfall ------'); -------------------------------------------------------------------------------- /chapter08/ch08.fs_chownSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_chownSync.js 5 | */ 6 | console.info("------ fs chownSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var statSync_pre = fs.statSync('txt/chownSync.txt'); // TODO: 获取文件信息(同步方法) 10 | console.info('txt/chownSync.txt file info: '); 11 | console.info(statSync_pre); // TODO: 打印输出文件信息 12 | console.info(); 13 | console.info('fs.chownSync() Done.'); 14 | console.info(); 15 | fs.chownSync('txt/chownSync.txt', 1001, 1001); // TODO: 更改文件所有权(同步方法) 16 | console.info('fs.chownSync() Done.'); 17 | console.info(); 18 | var statSync_suf = fs.statSync('txt/chownSync.txt'); // TODO: 获取文件信息(同步方法) 19 | console.info('txt/chownSync.txt file info: '); 20 | console.info(statSync_suf); // TODO: 打印输出文件信息 21 | console.info(); -------------------------------------------------------------------------------- /chapter08/ch08.fs_watchFile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-30. 3 | * 4 | * ch08.fs_watchFile.js 5 | */ 6 | console.info("------ fs watchFile() ------"); 7 | console.info(); 8 | var file_path = "txt/watchFile.txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | /** 11 | * 监控文件函数方法 12 | * 13 | * fs.watchFile(filename, [options], listener); 14 | */ 15 | fs.watchFile(file_path, function (curr, prev) { 16 | console.log('the current mtime is: ' + curr.mtime); 17 | console.log('the previous mtime was: ' + prev.mtime); 18 | /** 19 | * 监控文件函数方法 20 | * 21 | * fs.watch(filename, [options], [listener]); 22 | */ 23 | fs.watch(file_path, function (event, filename) { 24 | console.log('the event is: ' + event); 25 | console.log('the filename is: ' + filename); 26 | }); 27 | }); -------------------------------------------------------------------------------- /chapter09/ch09.querystring_parse.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-13. 3 | * 4 | * ch09.querystring_parse.js 5 | */ 6 | console.info("------ querystring parse() ------"); 7 | console.info(); 8 | var url = require('url');// TODO: 引入路径处理模块 9 | var querystring = require('querystring');// TODO: 引入路径处理模块 10 | /** 11 | * 测试 url.parse() 函数方法 12 | * @type {string} 13 | */ 14 | var queryUrl = "http://localhost:6666/index?name=king&gender=male&level=high"; 15 | console.info('typeof queryUrl is : ' + typeof url.parse(queryUrl)); 16 | console.info(); 17 | console.info('querystring.parse("queryUrl") is : '); 18 | var url_parse = url.parse(queryUrl).query; 19 | /** 20 | * 测试 querystring.parse() 函数方法 21 | * @type {*} 22 | */ 23 | var querystring_parse = querystring.parse(url_parse); 24 | console.info(querystring_parse); 25 | console.info(); -------------------------------------------------------------------------------- /chapter02/ch02.module-exchangerate-main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-exchangerate-main.js 5 | */ 6 | console.info("\n"); 7 | console.info("------汇率换算应用------"); 8 | console.info("\n"); 9 | var exRate = require('./ch02.module-exchangerate-obj.js'); // 加载自定义模块 10 | var readline = require('readline'); // 加载核心模块 11 | var rl = readline.createInterface({ 12 | input: process.stdin, 13 | output: process.stdout 14 | }); 15 | rl.question("Please enter count: ", function(iMoney) { 16 | // TODO: 调用dollar2rmb()方法将美元换算成人民币 17 | console.info(iMoney + ' US-Dollar exchange to RMB equals ' + exRate.dollar2rmb(iMoney)); 18 | // TODO: 调用rmb2dollar()方法将人民币换算成美元 19 | console.info(iMoney + ' RMB exchange to US-Dollar equals ' + exRate.rmb2dollar(iMoney)); 20 | console.info("\n"); 21 | rl.close(); 22 | }); -------------------------------------------------------------------------------- /chapter10/client/ch10.net_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-19. 3 | * 4 | * ch10.net_client.js 5 | */ 6 | console.info("------ net ServerClient() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 9696; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected...'); 16 | console.info(); 17 | }); 18 | /** 19 | * 为TCP客户端实例添加一个"data"事件处理函数 20 | */ 21 | client.on('data', function(data) { 22 | console.info('client on data...'); 23 | console.info(); 24 | }); 25 | /** 26 | * 为TCP客户端实例添加一个"end"事件处理函数 27 | */ 28 | client.on('end', function() { 29 | console.log('client disconnected'); 30 | console.info(); 31 | }); -------------------------------------------------------------------------------- /chapter09/ch09.url_parse_format.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-13. 3 | * 4 | * ch09.url_parse_format.js 5 | */ 6 | console.info("------ url parse() ------"); 7 | console.info(); 8 | var url = require('url');// TODO: 引入路径处理模块 9 | /** 10 | * 测试 url.parse() 函数方法 11 | * @type {string} 12 | */ 13 | var queryUrl = "http://localhost:6666/index?name=king&gender=male&level=high"; 14 | console.info('typeof queryUrl is : ' + typeof url.parse(queryUrl)); 15 | console.info(); 16 | console.info('url.parse("queryUrl") is : '); 17 | var url_parse = url.parse(queryUrl); // TODO: 调用url.parse()方法 18 | console.info(url_parse); 19 | console.info(); 20 | /** 21 | * 测试 url.format() 函数方法 22 | */ 23 | console.info('url.format("url_parse") is : '); 24 | var url_format = url.format(url_parse); // TODO: 调用url.format()方法 25 | console.info(url_format); 26 | console.info(); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_free.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-9. 3 | * 4 | * ch06.child_process_spawn_free.js 5 | */ 6 | console.info("------ child_process spawn free ------"); 7 | console.info(); 8 | /** 9 | * child_process spawn 10 | * 利用子进程获取系统内存使用情况 11 | * @type {exports.spawn|*} 12 | */ 13 | var spawn = require('child_process').spawn; // TODO: 引入child_process模块 14 | var free = spawn('free', ['-m']); // TODO: 定义命令行‘free -m’ 15 | /** 16 | * 捕获标准输出并将其打印到控制台 17 | */ 18 | free.stdout.on('data', function (data) { 19 | console.log('标准输出:\n' + data); 20 | }); 21 | /** 22 | * 捕获标准错误输出并将其打印到控制台 23 | */ 24 | free.stderr.on('data', function (data) { 25 | console.log('标准错误输出:\n' + data); 26 | }); 27 | /** 28 | * 注册子进程关闭事件 29 | */ 30 | free.on('exit', function (code, signal) { 31 | console.log('子进程已退出,代码: ' + code); 32 | }); -------------------------------------------------------------------------------- /chapter10/ServerConnection/ch10.net_connection_server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_connection_server.js 5 | */ 6 | console.info("------ net listening() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 创建 TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听"listening"事件 17 | */ 18 | server.on('listening', function() { 19 | console.log('Server is listening on port', PORT); 20 | console.info(); 21 | }); 22 | /** 23 | * 监听"connection"事件 24 | */ 25 | server.on('connection', function(socket) { 26 | console.log('Server has a new connection'); 27 | console.info(); 28 | }); 29 | /** 30 | * 调用server.listen()监听服务器端口 31 | */ 32 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /Chapter12/redirect/ch12.http_createServer_redirectB.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_createServer_redirectA.js 5 | */ 6 | console.info("------ http - create redirect server ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start HTTP server on port 8686..."); 10 | console.info(); 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | /** 16 | * 通过res.writeHeader()函数方法写HTTP文件头 17 | */ 18 | res.writeHead(200, {'Content-type' : 'text/html'}); 19 | /** 20 | * 通过res.write()函数方法写页面内容 21 | */ 22 | res.write('

Node.js --- HTTP

'); 23 | /** 24 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 25 | */ 26 | res.end('

Create Redirect HTTP Server on Port 8686!

'); 27 | }).listen(8686); // TODO: 监听8686端口号 -------------------------------------------------------------------------------- /chapter08/ch08.fs_openSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-20. 3 | * 4 | * ch08.fs_openSync.js 5 | */ 6 | console.info("------ fs openSync() ------"); 7 | console.info(); 8 | var exec = require('child_process').exec; // TODO: 引入child_process模块 9 | var child_pre = exec('cat txt/openSync.txt', 10 | function (error, stdout, stderr) { 11 | console.info('cat txt/openSync.txt stdout: '); 12 | console.log(stdout); // TODO: 打印输出 stdout 13 | console.log(stderr); // TODO: 打印输出 stderr 14 | }); 15 | console.info(); 16 | var fs = require('fs'); // TODO: 引入文件系统模块 17 | var fd = fs.openSync('txt/openSync.txt', 'a'); // TODO: 打开文件(同步方式) 18 | console.info("文件描述符: " + fd); 19 | console.log('fs.openSync() Done.'); 20 | console.info(); 21 | fs.closeSync(fd); 22 | console.info("文件描述符: " + fd); 23 | console.log('fs.closeSync() Done.'); 24 | console.info(); 25 | -------------------------------------------------------------------------------- /chapter10/note/ch10.net_listening_server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_listening_server.js 5 | */ 6 | console.info("------ net listening() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 7788; // TODO: 定义端口号 11 | var server = require('net').createServer(); 12 | server.on('listening', function() { 13 | console.log('Server is listening on port', PORT); 14 | }); 15 | server.on('connection', function(socket) { 16 | console.log('Server has a new connection'); 17 | socket.end(); 18 | server.close(); 19 | }); 20 | server.on('close', function() { 21 | console.log('Server is now closed'); 22 | }); 23 | server.on('error', function(err) { 24 | console.log('Error occurred:', err.message); 25 | }); 26 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /chapter01/ch01.console-tinyCLI.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/1/16. 3 | * 4 | * ch01.console-tinyCLI.js 5 | */ 6 | var readline = require('readline'); 7 | rl = readline.createInterface( 8 | process.stdin, 9 | process.stdout 10 | ); 11 | rl.setPrompt('NodeJS> '); 12 | rl.prompt(); 13 | rl.on('line', function(line) { 14 | switch(line.trim()) { 15 | case 'name': 16 | console.log('king!'); 17 | break; 18 | case 'code': 19 | console.log('Node.js!'); 20 | break; 21 | case 'time': 22 | console.log('2015!'); 23 | break; 24 | default: 25 | console.log('Say what? I might have heard `' + line.trim() + '`'); 26 | break; 27 | } 28 | rl.prompt(); 29 | }).on('close', function() { 30 | console.log('Have a great day!'); 31 | process.exit(0); 32 | }); 33 | -------------------------------------------------------------------------------- /chapter09/ch09.path_relative.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-9. 3 | * 4 | * ch09.path_relative.js 5 | */ 6 | console.info("------ path relative() ------"); 7 | console.info(); 8 | var path = require('path'); // TODO: 引入路径处理模块 9 | /** 10 | * 测试 path.resolve() 函数方法 11 | * @type {string} 12 | */ 13 | console.info("Current working directory : "); 14 | console.info(process.cwd()); 15 | console.info(); 16 | var path_a = "ch09.path_relative.js"; 17 | console.info('path.resolve("ch09.path_relative.js") is : '); 18 | var path_resolve_a = path.resolve(path_a); 19 | console.info(path_resolve_a); 20 | console.info(); 21 | var path_b = "test"; 22 | var path_c = "test.txt"; 23 | console.info('path.resolve("test","test.txt") is : '); 24 | var path_resolve_b = path.resolve(path_b, path_c); 25 | console.info("The relative path is : " + path.relative(path_resolve_a, path_resolve_b)); 26 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_readableB.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-3. 3 | * 4 | * ch11.stream_readable_readableB.js 5 | */ 6 | console.info("------ stream readable event ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var rs = fs.createReadStream('data/createReadStream.txt'); 13 | /** 14 | * 流(Stream)模块 --- 'readable'事件处理函数 15 | */ 16 | rs.on('readable', function() { 17 | console.log('readable event emitted.'); 18 | console.info(); 19 | }); 20 | /** 21 | * 流(Stream)模块 --- 'data'事件处理函数 22 | */ 23 | rs.on('data', function (chunk) { 24 | console.log('data event emitted.'); 25 | console.info(); 26 | }); 27 | /** 28 | * 流(Stream)模块 --- 'end'事件处理函数 29 | */ 30 | rs.on('end', function () { 31 | console.log('end event emitted.'); 32 | console.info(); 33 | }); -------------------------------------------------------------------------------- /chapter02/ch02.module-counter-main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-counter-main.js 5 | */ 6 | console.log(); 7 | var counter = require('./ch02.module-counter-obj.js'); 8 | console.log('第一次调用模块[ch02.module-counter-obj.js]'); 9 | counter.seOutputVal(10); //设置从10开始计数 10 | counter.setIncrement (10); //设置增量为10 11 | counter.printNextCount(); 12 | counter.printNextCount(); 13 | counter.printNextCount(); 14 | counter.printNextCount(); 15 | /** 16 | * require()多次调用同一模块不会重复加载 17 | */ 18 | var counter = require('./ch02.module-counter-obj.js'); 19 | console.log('第二次调用模块[ch02.module-counter-obj.js]'); 20 | counter.printNextCount(); 21 | counter.printNextCount(); 22 | counter.printNextCount(); 23 | counter.printNextCount(); 24 | counter.printNextCount(); 25 | /** 26 | * 自动清零操作 27 | */ 28 | console.log('自动清零操作'); 29 | counter.autoSetZero(); 30 | console.log(); -------------------------------------------------------------------------------- /Chapter12/redirect/ch12.http_createServer_redirectA.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_createServer_redirectA.js 5 | */ 6 | console.info("------ http - create redirect server ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start HTTP server on port 6868..."); 10 | console.info(); 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | /** 16 | * 通过res.writeHeader()函数方法写HTTP文件头 17 | */ 18 | res.writeHead(301, { 19 | 'Location': 'http://localhost:8686/' 20 | }); 21 | /** 22 | * 通过res.write()函数方法写页面内容 23 | */ 24 | res.write('

Node.js --- HTTP

'); 25 | /** 26 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 27 | */ 28 | res.end('

Create Redirect HTTP Server on Port 6868!

'); 29 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter03/ch03.async-doWhilst.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-doWhilst.js 5 | */ 6 | console.info('------ Node.js异步编程: Async doWhilst ------'); 7 | console.info(); 8 | var async = require('async'); 9 | var count = 0; 10 | /** 11 | * Define JSON Array 12 | * @type {{name: string, age: number}[]} 13 | */ 14 | var list = [ 15 | {name:'Jack',age:20}, 16 | {name:'Lucy',age:18}, 17 | {name:'Jack',age:20}, 18 | {name:'Lucy',age:18}, 19 | {name:'Lucy',age:18} 20 | ]; 21 | async.doWhilst( 22 | function (callback) { 23 | console.log(count); 24 | list[count].age += 1; 25 | count++; 26 | setTimeout(callback, 1000); 27 | }, 28 | function () { return count < 5; }, 29 | function (err) { 30 | console.log(list); 31 | } 32 | ); 33 | console.info(); 34 | console.info('------ Node.js异步编程: Async doWhilst ------'); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_exec_std.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-3. 3 | * 4 | * ch06.child_process_exec_std.js 5 | */ 6 | console.info("------ child_process exec std ------"); 7 | console.info(); 8 | /** 9 | * child_process exec 10 | * @type {exports.exec|*} 11 | */ 12 | var exec = require('child_process').exec; // TODO: 引入child_process模块 13 | var child = exec('cat ch06.child_process_exec_usage', 14 | function (error, stdout, stderr) { 15 | console.info('cat ch06.child_process_exec_usage.js stdout: '); 16 | console.log(stdout); // TODO: 打印输出 stdout 17 | console.info('cat ch06.child_process_exec_usage.js stderr: '); 18 | console.log(stderr); // TODO: 打印输出 stderr 19 | if (error !== null) { 20 | console.info('cat ch06.child_process_exec_usage.js error: '); 21 | console.log(error); // TODO: 打印输出错误信息 22 | } 23 | }); -------------------------------------------------------------------------------- /chapter02/mypackage/lib/sign.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-4. 3 | * 4 | * sign.js 5 | */ 6 | var sign_a, sign_b; 7 | console.info('随机生成运算符...'); 8 | exports.generate_sign_a = function() { 9 | sign_a = switchSign(Math.round(Math.random() * 3)); // TODO: 随机选取四则运算符 10 | return sign_a; 11 | } 12 | exports.generate_sign_b = function() { 13 | sign_b = switchSign(Math.round(Math.random() * 3)); // TODO: 随机选取四则运算符 14 | return sign_b; 15 | } 16 | /** 17 | * generate random sign 18 | * @param i 19 | * @returns {*} 20 | */ 21 | function switchSign(i) { 22 | var s; 23 | switch(i) { 24 | case 0: 25 | s = '+'; 26 | break; 27 | case 1: 28 | s = '-'; 29 | break; 30 | case 2: 31 | s = '*'; 32 | break; 33 | default: 34 | s = '/'; 35 | break; 36 | } 37 | return s; 38 | } -------------------------------------------------------------------------------- /chapter08/ch08.fs_fchownSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-21. 3 | * 4 | * ch08.fs_fchownSync.js 5 | */ 6 | console.info("------ fs fchownSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var fd = fs.openSync('txt/fchownSync.txt', 'r'); // TODO: 打开文件(同步方式) 10 | var fstatSync_pre = fs.fstatSync(fd); // TODO: 获取文件信息(同步方法) 11 | console.info('txt/fchownSync.txt file info: '); 12 | console.info(fstatSync_pre); // TODO: 打印输出文件信息 13 | console.info(); 14 | console.info('fs.fstatSync() Done.'); 15 | fs.fchownSync(fd, 1001, 1001); // TODO: 更改文件所有权(同步方法) 16 | console.info('fs.fchownSync() Done.'); 17 | console.info(); 18 | var fstatSync_suf = fs.fstatSync(fd); // TODO: 获取文件信息(同步方法) 19 | console.info('txt/fchownSync.txt file info: '); 20 | console.info(fstatSync_suf); // TODO: 打印输出文件信息 21 | console.info(); 22 | console.info('fs.fstatSync() Done.'); 23 | fs.closeSync(fd); 24 | console.info(); -------------------------------------------------------------------------------- /Chapter12/writeheader/ch12.http_response_writeheader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_response_writeheader.js 5 | */ 6 | console.info("------ http - server write header ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start HTTP server..."); 10 | console.info(); 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | /** 16 | * 通过res.writeHead()函数方法写HTTP文件头 17 | */ 18 | var body = 'write header'; 19 | res.writeHead(200, { 20 | 'Content-Length': body.length, 21 | 'Content-Type': 'text/plain' 22 | }); 23 | /** 24 | * 通过res.write()函数方法写页面内容 25 | */ 26 | res.write("Node.js"); 27 | res.write("HTTP"); 28 | /** 29 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 30 | */ 31 | res.end(); 32 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter10/ServerClient/ch10.sc_net_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.sc_net_client.js 5 | */ 6 | console.info("------ net ServerClient() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 9696; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | }); 19 | /** 20 | * 为TCP客户端实例添加一个"data"事件处理函数 21 | */ 22 | client.on('data', function(data) { 23 | console.log(data.toString()); 24 | console.info(); 25 | client.end(); 26 | }); 27 | /** 28 | * 为TCP客户端实例添加一个"end"事件处理函数 29 | */ 30 | client.on('end', function() { 31 | console.log('client disconnected'); 32 | console.info(); 33 | }); -------------------------------------------------------------------------------- /chapter10/note/ch10.net_listening_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_listening_client.js 5 | */ 6 | console.info("------ net ServerClient() ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 7788; // TODO: 定义端口号 11 | /** 12 | * 使用net.connect()函数方法创建一个TCP客户端实例 13 | */ 14 | var client = net.connect(PORT, HOST, function() { 15 | console.log('client connected'); 16 | console.info(); 17 | client.write('client write : Hello Server!'); 18 | }); 19 | /** 20 | * 为TCP客户端实例添加一个"data"事件处理函数 21 | */ 22 | client.on('data', function(data) { 23 | console.log(data.toString()); 24 | console.info(); 25 | client.end(); 26 | }); 27 | /** 28 | * 为TCP客户端实例添加一个"end"事件处理函数 29 | */ 30 | client.on('end', function() { 31 | console.log('client disconnected'); 32 | console.info(); 33 | }); -------------------------------------------------------------------------------- /chapter07/ch07.os_uptime.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-15. 3 | * 4 | * ch07.os_uptime.js 5 | */ 6 | console.info("------ OS uptime() ------"); 7 | console.info(); 8 | var os = require('os'); 9 | var uptime = os.uptime(); 10 | console.info('操作系统已经运行了: ' + uptime + ' seconds.'); 11 | console.info(); 12 | var sTime = convertTime(uptime); 13 | console.info('操作系统已经运行了: ' + sTime); 14 | console.info(); 15 | console.info("------ OS uptime() ------"); 16 | /** 17 | * Format time to Hours/Minutes/Seconds 18 | * @param uptime 19 | * @returns {string} 20 | */ 21 | function convertTime(uptime) { 22 | var runTime; 23 | var hour; 24 | var minute; 25 | var second; 26 | hour = parseInt(uptime / 3600); 27 | minute = parseInt((uptime - hour * 3600) / 60); 28 | second = uptime - hour * 3600 - minute * 60; 29 | runTime = hour + ' hours ' + minute + ' minutes ' + second + ' seconds.'; 30 | return runTime; 31 | } -------------------------------------------------------------------------------- /chapter03/ch03.async-auto.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-auto.js 5 | */ 6 | var async = require('async'); 7 | async.auto({ 8 | getData: function(callback){ 9 | callback(null, 'data', 'converted to array'); 10 | }, 11 | makeFolder: function(callback){ 12 | callback(null, 'folder'); 13 | }, 14 | writeFile: ['getData', 'makeFolder', function(callback, results){ 15 | callback(null, 'filename'); 16 | }], 17 | emailLink: ['writeFile', function(callback, results){ 18 | callback(null, {'file':results.writeFile, 'email':'user@example.com'}); 19 | }] 20 | }, function(err, results) { 21 | console.log('err = ', err); 22 | console.log('results = ', results); 23 | }); 24 | //auto(tasks, [callback]); 25 | //用来处理有依赖关系的多个任务的执行。 26 | //示例中writeFile依赖getData和makeFolder,emailLink依赖writeFile。 27 | //执行示例代码,将所有的results输出到控制台,观察输出顺序和内容。 28 | //存在多个依赖关系的时候,auto让代码变得简单了不少。 -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_ls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-30. 3 | * 4 | * ch06.child_process_spawn_ls.js 5 | */ 6 | console.info("------ child_process spawn ls ------"); 7 | console.info(); 8 | var spawn = require('child_process').spawn; // TODO: 引入child_process模块 9 | var ls_var = spawn('ls', ['-lh', '/usr']); // TODO: 定义命令行‘ls -lh /usr’ 10 | /** 11 | * 捕获控制台输出对象stdout,输出捕获数据 12 | */ 13 | ls_var.stdout.on('data', function (data) { 14 | console.log('stdout: ' + data); 15 | }); 16 | /** 17 | * 绑定系统‘error’事件 18 | */ 19 | ls_var.on('error', function (code) { 20 | console.log('child process error with code ' + code); 21 | }); 22 | /** 23 | * 绑定系统‘close’事件 24 | */ 25 | ls_var.on('close', function (code) { 26 | console.log('child process closed with code ' + code); 27 | }); 28 | /** 29 | * 绑定系统‘exit’事件 30 | */ 31 | ls_var.on('exit', function (code) { 32 | console.log('child process exited with code ' + code); 33 | }); -------------------------------------------------------------------------------- /chapter03/ch03.async-whilst.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-whilst.js 5 | */ 6 | console.info('------ Node.js异步编程: Async whilst ------'); 7 | console.info(); 8 | var async = require('async'); 9 | var count = 0; 10 | /** 11 | * Define JSON Array 12 | * @type {{name: string, age: number}[]} 13 | */ 14 | var list = [ 15 | {name:'Jack',age:20}, 16 | {name:'Lucy',age:18}, 17 | {name:'Jack',age:20}, 18 | {name:'Lucy',age:18}, 19 | {name:'Lucy',age:18} 20 | ]; 21 | async.whilst( 22 | function () { 23 | return count < 5; 24 | }, 25 | function (callback) { 26 | console.log(count); 27 | list[count].age += 1; 28 | count++; 29 | setTimeout(callback, 1000); 30 | }, 31 | function (err) { 32 | console.log(count); 33 | console.log(list); 34 | } 35 | ); 36 | console.info(); 37 | console.info('------ Node.js异步编程: Async whilst ------'); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_lserr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-30. 3 | * 4 | * ch06.child_process_spawn_lserr.js 5 | */ 6 | console.info("------ child_process spawn lserr ------"); 7 | console.info(); 8 | var spawn = require('child_process').spawn; // TODO: 引入child_process模块 9 | var ls_err = spawn('ls', ['-lh', '/err']); // TODO: 定义命令行‘ls -lh /usr’ 10 | /** 11 | * 捕获控制台错误对象stderr,输出捕获数据 12 | */ 13 | ls_err.stderr.on('data', function (data) { 14 | console.log('stderr: ' + data); 15 | }); 16 | /** 17 | * 绑定系统‘error’事件 18 | */ 19 | ls_err.on('error', function (code) { 20 | console.log('child process error with code ' + code); 21 | }); 22 | /** 23 | * 绑定系统‘close’事件 24 | */ 25 | ls_err.on('close', function (code) { 26 | console.log('child process closed with code ' + code); 27 | }); 28 | /** 29 | * 绑定系统‘exit’事件 30 | */ 31 | ls_err.on('exit', function (code) { 32 | console.log('child process exited with code ' + code); 33 | }); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_pid.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-3. 3 | * 4 | * ch06.child_process_spawn_pid.js 5 | */ 6 | console.info("------ child_process spawn pid ------"); 7 | console.info(); 8 | /** 9 | * child_process spawn 10 | * @type {exports.spawn|*} 11 | */ 12 | var spawn = require('child_process').spawn; // TODO: 引入child_process模块 13 | /** 14 | * grep child pid of node 15 | */ 16 | var grep_node = spawn('grep', ['node']); 17 | console.log('Spawned child pid of node: ' + grep_node.pid); 18 | grep_node.stdin.end(); 19 | console.info(); 20 | /** 21 | * grep child pid of top 22 | */ 23 | var grep_top = spawn('grep', ['top']); 24 | console.log('Spawned child pid of top: ' + grep_top.pid); 25 | grep_top.stdin.end(); 26 | console.info(); 27 | /** 28 | * grep child pid of ssh 29 | */ 30 | var grep_ssh = spawn('grep', ['ssh']); 31 | console.log('Spawned child pid of ssh: ' + grep_ssh.pid); 32 | grep_ssh.stdin.end(); 33 | console.info(); -------------------------------------------------------------------------------- /chapter06/ch06.child_process_spawn_ps.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-9. 3 | * 4 | * ch06.child_process_spawn_ps.js 5 | */ 6 | var spawn = require('child_process').spawn, 7 | ps = spawn('ps', ['ax']), 8 | grep = spawn('grep', ['ssh']); 9 | 10 | ps.stdout.on('data', function (data) { 11 | grep.stdin.write(data); 12 | }); 13 | 14 | ps.stderr.on('data', function (data) { 15 | console.log('ps stderr: ' + data); 16 | }); 17 | 18 | ps.on('close', function (code) { 19 | if (code !== 0) { 20 | console.log('ps process exited with code ' + code); 21 | } 22 | grep.stdin.end(); 23 | }); 24 | 25 | grep.stdout.on('data', function (data) { 26 | console.log('' + data); 27 | }); 28 | 29 | grep.stderr.on('data', function (data) { 30 | console.log('grep stderr: ' + data); 31 | }); 32 | 33 | grep.on('close', function (code) { 34 | if (code !== 0) { 35 | console.log('grep process exited with code ' + code); 36 | } 37 | }); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readFile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-28. 3 | * 4 | * ch08.fs_readFile.js 5 | */ 6 | console.info("------ fs readFile() ------"); 7 | console.info(); 8 | var file_path = "txt/readFile.txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | /** 11 | * 判断文件是否存在(异步方式) 12 | */ 13 | fs.exists(file_path, function (exists) { 14 | if (exists) { 15 | fs.readFile(file_path, 'utf-8', function (err, data) { 16 | if (err) { 17 | throw err; 18 | console.info(); 19 | } else { 20 | console.info('read txt/readFile.txt contents: '); 21 | console.info(data); // TODO: 打印输出文件内容 22 | console.info(); 23 | console.log('fs.readFile() Done.'); 24 | console.info(); 25 | } 26 | }); 27 | } else { 28 | console.info('err: ' + err); 29 | console.info(); 30 | } 31 | }); 32 | console.info(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_unpipe.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-5. 3 | * 4 | * ch11.stream_readable_unpipe.js 5 | */ 6 | console.info("------ stream pipe write file ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var readable = fs.createReadStream('data/srcUnFile.txt'); 13 | /** 14 | * 调用文件系统(fs)模块的createWriteStream()方法创建可写(Writable)流 15 | */ 16 | var writable = fs.createWriteStream('data/destUnFile.txt'); 17 | /** 18 | * 所有来自readable的数据会被写入到'data/destUnFile.txt'文本文件中 19 | */ 20 | readable.pipe(writable); 21 | /** 22 | * 通过setTimeout()方法设置1ms时间延迟 23 | * 并通过unpipe()方法解除pipe()方法设置的流 24 | * 最后自行关闭文件流 25 | */ 26 | setTimeout(function() { 27 | console.log('停止写入到 data/destUnFile.txt'); 28 | console.info(); 29 | readable.unpipe(writable); // TODO: 解除设置的流 30 | console.log('自行关闭文件流'); 31 | console.info(); 32 | writable.end(); // TODO: 关闭文件流 33 | }, 1); -------------------------------------------------------------------------------- /chapter10/SocketData/ch10.net_socketdata_clientA.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketdata_clientA.js 5 | */ 6 | console.info("------ net socketdata ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server A!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | client.end(); 27 | }); 28 | /** 29 | * 为TCP客户端实例添加一个"end"事件处理函数 30 | */ 31 | client.on('end', function() { 32 | console.log('client disconnected'); 33 | console.info(); 34 | }); -------------------------------------------------------------------------------- /chapter10/SocketData/ch10.net_socketdata_clientB.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketdata_clientB.js 5 | */ 6 | console.info("------ net socketdata ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server BB!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | client.end(); 27 | }); 28 | /** 29 | * 为TCP客户端实例添加一个"end"事件处理函数 30 | */ 31 | client.on('end', function() { 32 | console.log('client disconnected'); 33 | console.info(); 34 | }); -------------------------------------------------------------------------------- /chapter10/SocketData/ch10.net_socketdata_clientC.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketdata_clientC.js 5 | */ 6 | console.info("------ net socketdata ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server CCC!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | client.end(); 27 | }); 28 | /** 29 | * 为TCP客户端实例添加一个"end"事件处理函数 30 | */ 31 | client.on('end', function() { 32 | console.log('client disconnected'); 33 | console.info(); 34 | }); -------------------------------------------------------------------------------- /chapter10/SocketData/ch10.net_socketdata_clientD.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketdata_clientD.js 5 | */ 6 | console.info("------ net socketdata ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server DDDD!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | client.end(); 27 | }); 28 | /** 29 | * 为TCP客户端实例添加一个"end"事件处理函数 30 | */ 31 | client.on('end', function() { 32 | console.log('client disconnected'); 33 | console.info(); 34 | }); -------------------------------------------------------------------------------- /chapter10/SocketData/ch10.net_socketdata_clientE.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketdata_clientD.js 5 | */ 6 | console.info("------ net socketdata ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server EEEEE!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | client.end(); 27 | }); 28 | /** 29 | * 为TCP客户端实例添加一个"end"事件处理函数 30 | */ 31 | client.on('end', function() { 32 | console.log('client disconnected'); 33 | console.info(); 34 | }); -------------------------------------------------------------------------------- /Chapter12/httpget/ch12.http_response_get.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_response_get.js 5 | */ 6 | console.info("------ http - server get ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | var url = require('url'); // TODO: 引入url模块 10 | var qs = require('querystring'); // TODO: 引入querystring模块 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | /** 16 | * 通过res.writeHeader()函数方法写HTTP文件头 17 | */ 18 | res.writeHead(200, {'Content-type' : 'text/plain'}); 19 | /** 20 | * 通过url.parse()函数方法获取查询字段 21 | */ 22 | var query = url.parse(req.url).query; 23 | console.info(query); 24 | console.info(); 25 | /** 26 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 27 | */ 28 | var qs_parse = qs.parse(query); 29 | console.info(qs_parse); 30 | console.info(); 31 | res.end(JSON.stringify(qs_parse)); 32 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /Chapter12/pingserver/ch12.http_client_ping.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-18. 3 | * 4 | * ch12.http_client_ping.js 5 | */ 6 | console.info("------ http - client ping ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start ping HTTP server..."); 10 | console.info(); 11 | /** 12 | * 定义查询字段 13 | */ 14 | var options = { 15 | host: 'localhost', 16 | port: 6868, 17 | path: '/' 18 | }; 19 | /** 20 | * 自定义函数 ping_server() 21 | */ 22 | function ping_server() { 23 | /** 24 | * 发送 HTTP GET 请求 25 | */ 26 | http.get(options, function(res) { 27 | if (res.statusCode == 200) { 28 | console.log("The site is up!"); 29 | } 30 | else { 31 | console.log("The site is down!"); 32 | } 33 | }).on('error', function(e) { 34 | console.log("There was an error: " + e.message); 35 | }); 36 | } 37 | /** 38 | * 通过setInterval()函数方法设定时间间隔 39 | */ 40 | setInterval(ping_server, 1000); -------------------------------------------------------------------------------- /chapter05/ch05.process-nextTick.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-23. 3 | * 4 | * ch05.process-nextTick.js 5 | */ 6 | console.info("------ Process nextTick ------"); 7 | console.info(); 8 | /** 9 | * 使用setTimeout()方法执行异步操作 10 | */ 11 | console.time('startB'); // TODO: console.time()计时器B 12 | console.log('start - setTimeout'); 13 | /** 14 | * setTimeout()方法 15 | */ 16 | setTimeout(function() { 17 | console.log('nextTick callback 2'); 18 | }, 0); 19 | console.log('scheduled - setTimeout'); 20 | console.timeEnd('startB'); // TODO: console.time()计时器B 21 | /** 22 | * 使用process.nextTick()方法执行异步操作 23 | */ 24 | console.time('startA'); // TODO: console.time()计时器A 25 | console.log('start - nextTick'); 26 | /** 27 | * process.nextTick()方法 28 | */ 29 | process.nextTick(function() { 30 | console.log('nextTick callback 1'); 31 | }); 32 | console.log('scheduled - nextTick'); 33 | console.timeEnd('startA'); // TODO: console.time()计时器A 34 | console.info(); 35 | console.info("------ Process nextTick ------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_open.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-20. 3 | * 4 | * ch08.fs_open.js 5 | */ 6 | console.info("------ fs open() ------"); 7 | console.info(); 8 | var exec = require('child_process').exec; // TODO: 引入child_process模块 9 | var child_pre = exec('cat txt/open.txt', 10 | function (error, stdout, stderr) { 11 | console.info('cat txt/open.txt stdout: '); 12 | console.log(stdout); // TODO: 打印输出 stdout 13 | console.log(stderr); // TODO: 打印输出 stderr 14 | }); 15 | var fs = require('fs'); // TODO: 引入文件系统模块 16 | /** 17 | * 打开文件(异步方式) 18 | */ 19 | fs.open('txt/open.txt', 'a', function (err, fd) { 20 | if (err) { 21 | throw err; 22 | } else { 23 | console.info("文件描述符: " + fd); 24 | console.log('fs.open() Done'); 25 | console.info(); 26 | } 27 | fs.close(fd, function () { 28 | console.info("文件描述符: " + fd); 29 | console.log('fs.close() Done'); 30 | console.info(); 31 | }); 32 | }); 33 | console.info(); -------------------------------------------------------------------------------- /chapter08/ch08.fs_readlink.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-23. 3 | * 4 | * ch08.fs_readlink.js 5 | */ 6 | console.info("------ fs readlink() ------"); 7 | console.info(); 8 | var srcpath = "txt/symlink.txt"; 9 | var linkpath = "txtlink/symlink.txt"; 10 | var fs = require('fs'); // TODO: 引入文件系统模块 11 | /** 12 | * 读取链接文件(异步方式) 13 | */ 14 | fs.readlink(srcpath, function (err, linkString) { 15 | if (err) { 16 | // throw err; 17 | console.info('err: ' + err); 18 | /** 19 | * 读取链接文件(异步方式) 20 | */ 21 | fs.readlink(linkpath, function (err, linkString) { 22 | if (err) { 23 | throw err; 24 | } else { 25 | console.info('read linkpath: ' + linkString); 26 | console.log('fs.readlink() Done.'); 27 | } 28 | }); 29 | console.info(); 30 | } else { 31 | console.info('read srcpath: ' + linkString); 32 | console.log('fs.readlink() Done.'); 33 | } 34 | }); 35 | console.info(); -------------------------------------------------------------------------------- /Chapter12/statuscodes/ch12.http_response_statuscodes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-10. 3 | * 4 | * ch12.http_response_statuscodes.js 5 | */ 6 | console.info("------ http STSTUS_CODES ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | console.log("Now start HTTP server..."); 10 | console.info(); 11 | /** 12 | * 调用http.createServer()函数方法创建服务器 13 | */ 14 | http.createServer(function(req, res) { 15 | var status = req.url.substr(1); // TODO: 获取url查询字段 16 | var status_codes = status.substring(12); // TODO: 获取HTTP.STATUS_CODES 17 | /** 18 | * 判断http.STATUS_CODES响应状态码集合是否有效 19 | */ 20 | if(!http.STATUS_CODES[status_codes]) { 21 | status_codes = '404'; 22 | } 23 | /** 24 | * 通过res.writeHeader()函数方法写HTTP文件头 25 | */ 26 | res.writeHeader(status_codes, {'Content-Type':'text/plain'}); 27 | /** 28 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 29 | */ 30 | res.end(http.STATUS_CODES[status_codes]); 31 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter04/ch04.buffer-copy.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-copy.js 5 | */ 6 | console.info("------ Buffer copy ------"); 7 | console.info(); 8 | /** 9 | * define Buffer obj 10 | * @type {Buffer} 11 | */ 12 | buf1 = new Buffer(26); 13 | buf2 = new Buffer(26); 14 | /** 15 | * init a new Buffer obj 16 | */ 17 | for(var i=0; i<26; i++) { 18 | buf1[i] = i + 97; // TODO: 97 is ASCII 'a' 19 | buf2[i] = 35; // TODO: ASCII '#' 20 | } 21 | buf1.copy(buf2, 6, 0, 10); // TODO: Buffer copy 22 | console.log(buf2.toString('ascii', 0, 25)); 23 | console.log(); 24 | /** 25 | * define Buffer obj 26 | * @type {Buffer} 27 | */ 28 | buf = new Buffer(26); 29 | /** 30 | * init a new Buffer obj 31 | */ 32 | for(var i=0; i<26; i++) { 33 | buf[i] = i + 97; // TODO: 97 is ASCII 'a' 34 | } 35 | console.info(buf.toString()); 36 | console.log(); 37 | buf.copy(buf, 0, 6, 10); // TODO: Buffer copy 38 | console.log(buf.toString()); 39 | console.info(); 40 | console.info("------ Buffer copy ------"); -------------------------------------------------------------------------------- /chapter01/ch01.console-factorial.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-10. 3 | * 4 | * ch01.console-factorial.js 5 | */ 6 | console.info("\n"); 7 | console.info("------阶乘计算------"); 8 | console.info("\n"); 9 | var iNum, iFactorial=1; // TODO: 定义并初始化变量 10 | var strFactorial; // TODO: 定义字符串变量,用于阶乘运算结果输出 11 | // TODO: 从控制台读取用户输入 12 | var readline = require('readline'); 13 | var rl = readline.createInterface({ 14 | input: process.stdin, 15 | output: process.stdout 16 | }); 17 | rl.question("请输入阶乘运算起始数值:\nn = ", function(iNum) { 18 | // TODO: 计算阶乘结果 19 | strFactorial = iNum + "! = " + factorial(iNum); 20 | console.info(strFactorial); // 输出计算结果 21 | console.info("\n"); 22 | rl.close(); 23 | }); 24 | /** 25 | * 定义阶乘运算的递归方法 26 | */ 27 | function factorial(n) { 28 | if(n > 0) 29 | { 30 | if(n == 1) 31 | { 32 | iFactorial = 1; 33 | } 34 | else 35 | { 36 | iFactorial = n * factorial(n-1); 37 | } 38 | } 39 | return iFactorial; 40 | } 41 | -------------------------------------------------------------------------------- /chapter10/ServerClose/ch10.net_close_server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-21. 3 | * 4 | * ch10.net_close_server.js 5 | */ 6 | console.info("------ net close() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | /** 12 | * 创建 TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听"listening"事件 17 | */ 18 | server.on('listening', function() { 19 | console.log('Server is listening on port', PORT); 20 | console.info(); 21 | }); 22 | /** 23 | * 监听"connection"事件 24 | */ 25 | server.on('connection', function(socket) { 26 | console.log('Server has a new connection'); 27 | console.info(); 28 | server.close(); // TODO: 调用server.close()方法 29 | }); 30 | /** 31 | * 监听"close"事件 32 | */ 33 | server.on('close', function() { 34 | console.log('Server is now closed'); 35 | console.info(); 36 | }); 37 | /** 38 | * 调用server.listen()监听服务器端口 39 | */ 40 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /Chapter12/express-ajax/public/ajax.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Express - Ajax 7 | 8 | 9 | 21 | 22 |

Express - Ajax

23 | 24 |

25 | 点击调用 - jsonp
26 |
27 |

28 | 29 |

30 | 点击调用 - json
31 |
32 |

33 | 34 | -------------------------------------------------------------------------------- /chapter10/SocketWrite/ch10.net_socketwrite_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_socketwrite_client.js 5 | */ 6 | console.info("------ net socketwrite ------"); 7 | console.info(); 8 | var net = require("net"); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 8877; // TODO: 定义端口号 11 | var sWriteContent = "client write : Hello Server!"; // TODO: 定义字符串数据 12 | /** 13 | * 使用net.connect()函数方法创建一个TCP客户端实例 14 | */ 15 | var client = net.connect(PORT, HOST, function() { 16 | console.log('client connected'); 17 | console.info(); 18 | client.write(sWriteContent); 19 | }); 20 | /** 21 | * 为TCP客户端实例添加一个"data"事件处理函数 22 | */ 23 | client.on('data', function(data) { 24 | console.log(data.toString()); 25 | console.info(); 26 | console.info('socket.bytesRead is ' + client.bytesRead); 27 | console.info(); 28 | client.end(); 29 | }); 30 | /** 31 | * 为TCP客户端实例添加一个"end"事件处理函数 32 | */ 33 | client.on('end', function() { 34 | console.log('client disconnected'); 35 | console.info(); 36 | }); -------------------------------------------------------------------------------- /Chapter14/ch14.mysql_query.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-25. 3 | * 4 | * ch14.mysql_query.js 5 | */ 6 | console.info("------ mysql query() ------"); 7 | console.info(); 8 | var http = require("http"); // TODO: 引入HTTP模块 9 | var mysql = require('/usr/local/lib/node_modules/mysql'); // TODO: 引入mysql模块 10 | console.log("Now start HTTP server on port 6868..."); 11 | console.info(); 12 | /** 13 | * 创建数据库连接 14 | */ 15 | var connection = mysql.createConnection({ 16 | host: "localhost", // TODO: 主机地址 17 | user: "root", // TODO: 数据库用户名 18 | password: "root", // TODO: 数据库密码 19 | database: "nodejs", // TODO: 数据库名称 20 | port: 3306 // TODO: 端口号 21 | }); 22 | /** 23 | * 创建HTTP服务器 24 | */ 25 | http.createServer(function (req, res) { 26 | connection.query('select * from userinfo;', function (error, rows, fields) { 27 | res.writeHead(200, { "Content-Type": "text/html;charset=utf8" }); 28 | res.write("

测试 Node.js - MySQL 数据库查询操作!


"); 29 | res.end(JSON.stringify(rows)); 30 | }); 31 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter01/ch01.console-primeNum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-10. 3 | * 4 | * ch01.console-primeNum.js 5 | */ 6 | var i, j, iNum, strPrimeNum; 7 | var bFlag; // TODO: 定义该变量用于标记是否为质数 8 | var readline = require('readline'); 9 | var rl = readline.createInterface({ 10 | input: process.stdin, 11 | output: process.stdout 12 | }); 13 | /** 14 | * TODO: 用户输入一个整数作为上限,通过程序计算从2开始到该整数之间的全部质数 15 | */ 16 | rl.question("Please enter number? ", function(iNum) { 17 | // TODO: Calculate prime number 18 | strPrimeNum = " 2 "; 19 | for(i=3; i<=iNum; i++) // TODO: 利用for循环计算质数 20 | { 21 | bFlag = true; 22 | for(j=2; j ", strPrimeNum); // TODO: 打印输出质数序列 36 | rl.close(); 37 | }); -------------------------------------------------------------------------------- /chapter10/UDPServerClient/ch10.udp_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.udp_client.js 5 | */ 6 | console.info("------ UDP ServerClient ------"); 7 | console.info(); 8 | var dgram = require('dgram'); // TODO: 引入网络(UDP)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 12345; // TODO: 定义端口号 11 | var message = new Buffer('UDP Client to Server : Hello Server!'); 12 | /** 13 | * 创建UDP客户端 14 | */ 15 | console.info('Now create UDO Client...'); 16 | console.info(); 17 | /** 18 | * 使用dgram.createSocket函数方法创建一个UDP客户端 19 | */ 20 | var client = dgram.createSocket('udp4'); 21 | /** 22 | * 向服务器发送UDP数据报 23 | */ 24 | client.send(message, 0, message.length, PORT, HOST, function(err, bytes) { 25 | if (err) throw err; 26 | console.log('UDP message sent to ' + HOST +':'+ PORT); 27 | console.info(); 28 | console.info(bytes); 29 | console.info(); 30 | client.close(); 31 | }); 32 | /** 33 | * 为UDP客户端添加一个"close"事件处理函数 34 | */ 35 | client.on('close', function() { 36 | console.log('client disconnected'); 37 | console.info(); 38 | }); -------------------------------------------------------------------------------- /chapter03/ch03.asyn-closure.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-11. 3 | * 4 | * ch03.asyn-closure.js 5 | */ 6 | function func() { // TODO: 定义func函数实现闭包 7 | var n = 1; // TODO: 初始化局部变量 8 | nAdd = function () { // TODO: 全局变量nAdd实现的匿名函数实际也是闭包函数 9 | n++; // TODO: 实现局部变量 n 的自加操作 10 | } 11 | // TODO: 定义closure()显式闭包函数 12 | function closure() { 13 | console.info(n); // TODO: 打印变量 14 | } 15 | return closure; // TODO: 返回闭包函数 16 | } 17 | var print_n = func(); // TODO: 将函数func()赋给变量 print_n 18 | print_n(); // TODO: 打印func()函数中的局部变量 n(=1) 19 | nAdd(); // TODO: 调用全局变量nAdd 20 | print_n(); // TODO: 打印func()函数中的局部变量 n(=2) 21 | 22 | /*在这段代码中,result实际上就是闭包f2函数。它一共运行了两次,第一次的值是999,第二次的值是1000。这证明了,函数f1中的局部变量n一直保存在内存中,并没有在f1调用后被自动清除。 23 | 为什么会这样呢?原因就在于f1是f2的父函数,而f2被赋给了一个全局变量,这导致f2始终在内存中,而f2的存在依赖于f1,因此f1也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。 24 | 这段代码中另一个值得注意的地方,就是“nAdd=function(){n+=1}”这一行,首先在nAdd前面没有使用var关键字,因此 nAdd是一个全局变量,而不是局部变量。其次,nAdd的值是一个匿名函数(anonymous function),而这个 25 | 匿名函数本身也是一个闭包,所以nAdd相当于是一个setter,可以在函数外部对函数内部的局部变量进行操作。*/ 26 | -------------------------------------------------------------------------------- /chapter10/UDPClient/ch10.udp_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.udp_client.js 5 | */ 6 | console.info("------ UDP Client ------"); 7 | console.info(); 8 | var dgram = require('dgram'); // TODO: 引入网络(UDP)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 12345; // TODO: 定义端口号 11 | var message = new Buffer('UDP Client to Server : Hello Server!'); // TODO: 定义数据包 12 | /** 13 | * 创建UDP客户端 14 | */ 15 | console.info('Now create UDO Client...'); 16 | console.info(); 17 | /** 18 | * 使用dgram.createSocket函数方法创建一个UDP客户端 19 | */ 20 | var client = dgram.createSocket('udp4'); 21 | /** 22 | * 向服务器发送UDP数据报 23 | */ 24 | client.send(message, 0, message.length, PORT, HOST, function(err, bytes) { 25 | if(err) { 26 | throw err; 27 | } 28 | console.log('UDP message sent to...'); 29 | console.info(); 30 | /** 31 | * 关闭客户端 32 | */ 33 | client.close(); 34 | }); 35 | /** 36 | * 为UDP客户端添加一个"close"事件处理函数 37 | */ 38 | client.on('close', function() { 39 | console.log('client disconnected'); 40 | console.info(); 41 | }); -------------------------------------------------------------------------------- /Chapter12/httpget/ch12.http_request_get.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-16. 3 | * 4 | * ch12.http_request_get.js 5 | */ 6 | console.info("------ http - client get ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 发送 HTTP GET 请求 11 | */ 12 | http.get("http://localhost:6868/wechat?signature=12345678&echostr=78787878×tamp=168", 13 | /** 14 | * GET 回调函数 15 | * @param res 16 | */ 17 | function(res) { 18 | console.log('STATUS: ' + res.statusCode); // TODO: 打印输出Status_Codes响应状态码 19 | console.info(); 20 | res.setEncoding('utf8'); 21 | /** 22 | * 监听"data"事件处理函数 23 | */ 24 | res.on('data', function (chunk) { 25 | console.log('BODY: ' + chunk); // TODO: 打印输出服务器回写内容 26 | console.info(); 27 | }); 28 | console.info(); 29 | }).on('error', 30 | /** 31 | * “error”事件回调函数 32 | * @param e 33 | */ 34 | function(e) { 35 | console.log("Got error: " + e.message); // TODO: 打印输出“error”信息 36 | console.info(); 37 | }); -------------------------------------------------------------------------------- /chapter04/ch04.buffer-toString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/15. 3 | * 4 | * ch04.buffer-toString.js 5 | */ 6 | console.info("------ Buffer toString ------"); 7 | console.info(); 8 | // TODO: define a buffer obj 9 | buf = new Buffer(26); 10 | // TODO: init a buffer obj 11 | for (var i = 0 ; i < 26 ; i++) { 12 | buf[i] = i + 97; // TODO: 97 is ASCII 'a' 13 | } 14 | // TODO: outputs: abcdefghijklmnopqrstuvwxyz 15 | console.info("buf.toString('ascii'): " + buf.toString('ascii')); 16 | console.info(); 17 | // TODO: outputs: abcde 18 | console.info("buf.toString('ascii', 0, 5): " + buf.toString('ascii', 0, 5)); 19 | console.info(); 20 | // TODO: outputs: abcde 21 | console.info("buf.toString('utf8', 0, 8): " + buf.toString('utf8', 0, 8)); 22 | console.info(); 23 | // TODO: outputs: abcde 24 | console.info("buf.toString('hex', 0, 8): " + buf.toString('hex', 0, 12)); 25 | console.info(); 26 | // TODO: encoding defaults to 'utf8', outputs abcde 27 | console.info("buf.toString(undefined, 0, 18): " + buf.toString(undefined, 0, 18)); 28 | console.info(); 29 | console.info("------ Buffer toString ------"); -------------------------------------------------------------------------------- /chapter10/createServer/ch10.net_createServer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-19. 3 | * 4 | * ch10.net_createServer.js 5 | */ 6 | console.info("------ net createServer() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 9696; // TODO: 定义端口号 11 | /** 12 | * 使用net.ServerClient()函数方法创建一个TCP服务器实例 13 | * 同时调用listen()函数方法开始监听指定端口 14 | * 传入net.ServerClient()的回调函数将作为”connection“事件的处理函数 15 | */ 16 | console.info('Now create Server...'); 17 | console.info(); 18 | net.createServer(function(sock) { 19 | /** 20 | * 打印输出服务器监听提示信息 21 | */ 22 | console.log('Server listening on ' + HOST +':'+ PORT); // TODO: 服务器已经建立连接 23 | console.info(); 24 | /** 25 | * 为socket实例添加一个"data"事件处理函数 26 | */ 27 | sock.on('data', function(data) { 28 | console.log('socket on data...'); 29 | }); 30 | /** 31 | * 为socket实例添加一个"close"事件处理函数 32 | */ 33 | sock.on('close', function(data) { 34 | console.log('socket on close...'); 35 | }); 36 | 37 | }).listen(PORT, HOST); -------------------------------------------------------------------------------- /chapter05/ch05.process-sysinfo.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-3-22. 3 | * 4 | * ch05.process-sysinfo.js 5 | */ 6 | console.info("------ Process System Info ------"); 7 | console.info(); 8 | console.info('当前进程id:'); 9 | console.info(process.pid); 10 | console.info(); 11 | console.info('当前进程名称:'); 12 | console.info(process.title); 13 | console.info(); 14 | console.info('Node.js版本号:'); 15 | console.info(process.version); 16 | console.info(); 17 | console.info('Node.js版本属性:'); 18 | console.info(process.versions); 19 | console.info(); 20 | console.info('Node.js配置选项:'); 21 | console.info(process.config); 22 | console.info(); 23 | console.info('当前系统平台:'); 24 | console.info(process.platform); 25 | console.info(); 26 | console.info('当前CPU架构:'); 27 | console.info(process.arch); 28 | console.info(); 29 | console.info('运行当前进程可执行文件的绝对路径:'); 30 | console.info(process.execPath); 31 | console.info(); 32 | console.info('当前进程的命令行参数数组:'); 33 | console.info(process.argv); 34 | console.info(); 35 | console.info('指向当前shell的环境变量:'); 36 | console.info(process.env); 37 | console.info(); 38 | console.info("------ Process System Info ------"); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_read.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-3. 3 | * 4 | * ch11.stream_readable_read.js 5 | */ 6 | console.info("------ stream read() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var rs = fs.createReadStream('data/read.txt'); 13 | /** 14 | * 调用readable.setEncoding()函数方法设置编码 15 | */ 16 | rs.setEncoding('utf8'); 17 | /** 18 | * 流(Stream)模块 --- 'readable'事件处理函数 19 | */ 20 | rs.on('readable', function() { 21 | console.log('readable event emitted.'); 22 | console.info(); 23 | var chunk; 24 | while (null !== (chunk = rs.read())) { 25 | console.log('得到了 %d 字节的数据', chunk.length); 26 | console.info(); 27 | console.log('读取到的数据: ', chunk); 28 | console.info(); 29 | } 30 | }); 31 | rs.on('end', function () { 32 | console.log('end event emitted.'); 33 | console.info(); 34 | }); 35 | /** 36 | * 流(Stream)模块 --- 'close'事件处理函数 37 | */ 38 | rs.on('close', function () { 39 | console.log('close event emitted.'); 40 | console.info(); 41 | }); -------------------------------------------------------------------------------- /chapter08/ch08.fs_renameSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-17. 3 | * 4 | * ch08.fs_renameSync.js 5 | */ 6 | console.info("------ fs rename() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | console.time('fs-rename-syn'); // TODO: 定义时间开始标记 10 | fs.renameSync('txt/helloworld-syn.txt', 'txt/helloworld-syn-rename.txt'); // TODO: 文件重命名 11 | console.timeEnd('fs-rename-syn'); // TODO: 定义时间结束标记 12 | console.info(); 13 | var exec = require('child_process').exec; // TODO: 引入child_process模块 14 | var child_pre = exec('cat txt/helloworld-syn.txt', 15 | function (error, stdout, stderr) { 16 | console.info('cat txt/helloworld-syn.txt stdout: '); 17 | console.log(stdout); // TODO: 打印输出 stdout 18 | console.log(stderr); // TODO: 打印输出 stderr 19 | }); 20 | console.info(); 21 | var child_suf = exec('cat txt/helloworld-syn-rename.txt', 22 | function (error, stdout, stderr) { 23 | console.info('cat txt/helloworld-syn-rename.txt stdout: '); 24 | console.log(stdout); // TODO: 打印输出 stdout 25 | console.log(stderr); // TODO: 打印输出 stdout 26 | }); -------------------------------------------------------------------------------- /Chapter12/header/ch12.http_response_header.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-14. 3 | * 4 | * ch12.http_response_header.js 5 | */ 6 | console.info("------ http - create basic server ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 调用http.createServer()函数方法创建服务器 11 | */ 12 | http.createServer(function(req, res) { 13 | /** 14 | * 通过res.setHeader()函数方法设定HTTP文件头 15 | */ 16 | res.setHeader("Content-Type", "text/html"); 17 | res.setHeader("Set-Cookie", ["type=king", "language=javascript"]); 18 | /** 19 | * 通过res.getHeader()函数方法获取HTTP文件头 20 | */ 21 | var content_Type = res.getHeader('Content-Type'); 22 | console.info(content_Type); 23 | var set_cookie = res.getHeader('Set-Cookie'); 24 | console.info(set_cookie); 25 | /** 26 | * 通过res.write()函数方法写页面内容 27 | */ 28 | res.write('

Node.js --- HTTP

'); 29 | res.write('

' + content_Type + '

'); 30 | res.write('

' + set_cookie + '

'); 31 | /** 32 | * 通过res.end()函数方法发送响应状态码,并通知服务器消息完成 33 | */ 34 | res.end(); 35 | }).listen(6868); // TODO: 监听6868端口号 -------------------------------------------------------------------------------- /chapter10/UDPError/ch10.udp_error_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.udp_error_client.js 5 | */ 6 | console.info("------ UDP Error ------"); 7 | console.info(); 8 | var dgram = require('dgram'); // TODO: 引入网络(UDP)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 12345; // TODO: 定义端口号 11 | var message = new Buffer('UDP Client to Server : Hello Server!'); 12 | /** 13 | * 创建UDP客户端 14 | */ 15 | console.info('Now create UDO Client...'); 16 | console.info(); 17 | /** 18 | * 使用dgram.createSocket函数方法创建一个UDP客户端 19 | */ 20 | var client = dgram.createSocket('udp4'); 21 | /** 22 | * 向服务器发送UDP数据报 23 | */ 24 | client.send(message, 50, message.length, PORT, HOST, function(err, bytes) { 25 | if(err) { 26 | throw err; 27 | } else { 28 | console.log('UDP message sent to ' + HOST +':'+ PORT); 29 | console.info(); 30 | console.info(bytes); 31 | console.info(); 32 | } 33 | client.close(); 34 | }); 35 | /** 36 | * 为UDP客户端添加一个"close"事件处理函数 37 | */ 38 | client.on('close', function() { 39 | console.log('client disconnected'); 40 | console.info(); 41 | }); -------------------------------------------------------------------------------- /chapter10/ServerAddress/ch10.net_server_address.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-20. 3 | * 4 | * ch10.net_server_address.js 5 | */ 6 | console.info("------ net server.address() ------"); 7 | console.info(); 8 | var net = require('net'); // TODO: 引入网络(Net)模块 9 | var HOST = '127.0.0.1'; // TODO: 定义服务器地址 10 | var PORT = 7878; // TODO: 定义端口号 11 | /** 12 | * 创建 TCP服务器 13 | */ 14 | var server = net.createServer(); 15 | /** 16 | * 监听"listening"事件 17 | */ 18 | server.on('listening', function() { 19 | console.log('Server is listening on port', PORT); 20 | console.info(); 21 | var addr = server.address(); 22 | console.info("opened server on "); 23 | console.info("%j", addr); 24 | console.info(); 25 | server.close(); 26 | }); 27 | /** 28 | * 监听"close"事件 29 | */ 30 | server.on('close', function() { 31 | console.log('Server is now closed'); 32 | console.info(); 33 | }); 34 | /** 35 | * 监听"error"事件 36 | */ 37 | server.on('error', function(err) { 38 | console.log('Error occurred:', err.message); 39 | console.info(); 40 | }); 41 | /** 42 | * 调用server.listen()监听服务器端口 43 | */ 44 | server.listen(PORT, HOST); -------------------------------------------------------------------------------- /chapter04/ch04.buffer-concat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/17. 3 | * 4 | * ch04.buffer-concat.js 5 | */ 6 | console.info("------ Buffer concat vs String concat ------"); 7 | console.info(); 8 | /** 9 | * define variable 10 | * @type {Buffer} 11 | */ 12 | var buf = new Buffer("this is Buffer concat test!"); 13 | var str = "this is String concat test!"; 14 | /** 15 | * start record time 16 | */ 17 | console.time("buffer concat test!"); 18 | var list = []; 19 | var len = 100000 * buf.length; 20 | for(var i=0; i<100000; i++){ 21 | list.push(buf); 22 | len += buf.length; 23 | } 24 | /** 25 | * Buffer 对象拼接 26 | */ 27 | Buffer.concat(list, len); 28 | // var s1 = Buffer.concat(list, len).toString(); 29 | console.timeEnd("buffer concat test!"); 30 | console.info(); 31 | console.time("string concat test!"); 32 | var list = []; 33 | for(var i=100000; i>=0; i--) { 34 | list.push(str); 35 | } 36 | /** 37 | * String 对象拼接 38 | * @type {string} 39 | */ 40 | var s2 = list.join(""); 41 | console.timeEnd("string concat test!"); 42 | /** 43 | * end record time 44 | */ 45 | console.info(); 46 | console.info("------ Buffer concat vs String concat ------"); -------------------------------------------------------------------------------- /chapter08/ch08.fs_writeFileSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-29. 3 | * 4 | * ch08.fs_writeFileSync.js 5 | */ 6 | console.info("------ fs writeFileSync() ------"); 7 | console.info(); 8 | var file_path = "txt/writeFileSync.txt"; 9 | var fs = require('fs'); // TODO: 引入文件系统模块 10 | if(fs.existsSync(file_path)) { 11 | var file_contents_pre = fs.readFileSync(file_path, 'utf-8'); // TODO: 读文件(同步方式) 12 | console.info('read txt/writeFileSync.txt contents: '); 13 | console.info(file_contents_pre); // TODO: 打印输出文件内容 14 | console.log('fs.readFileSync() Done.'); 15 | console.info(); 16 | console.info('write to txt/writeFileSync.txt : '); 17 | fs.writeFileSync(file_path, 'fs.writeFileSync()'); // TODO: 写文件(同步方式) 18 | console.log('fs.writeFileSync() Done.'); 19 | console.info(); 20 | var file_contents_suf = fs.readFileSync(file_path, 'utf-8'); // TODO: 读文件(同步方式) 21 | console.info('read txt/writeFileSync.txt contents: '); 22 | console.info(file_contents_suf); // TODO: 打印输出文件内容 23 | console.log('fs.readFileSync() Done.'); 24 | console.info(); 25 | } else { 26 | console.log(file_path + 'is not exists.'); 27 | console.info(); 28 | } -------------------------------------------------------------------------------- /chapter02/ch02.module-packagejson.json: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | * 4 | * ch02.module-packagejson.json 5 | */ 6 | { 7 | 8 | "name": "myNodeJSApp", 9 | "version": "0.0.1", 10 | "author" : "king", 11 | "description" : "Introduce to Nodejs Package.json", 12 | "main" : "./lib/main.js", 13 | "keywords" : "javascript, node.js", 14 | "respository" : { 15 | "type" : "git", 16 | "url" :"http://url" 17 | }, 18 | "bugs" : [ 19 | { 20 | "url" : "http://url/bug", 21 | "email" : "bug@example.com" 22 | } 23 | ], 24 | "contributors" : [ 25 | { 26 | "name" : "xxx", 27 | "email" : "xxx@example.com" 28 | } 29 | ], 30 | "license" : "MIT", 31 | "engines" : { "node" : "0.10.x"}, 32 | "script" : { 33 | "start" : "node index.js" 34 | }, 35 | "private": true, 36 | "scripts": { 37 | "start": "node ./bin/www" 38 | }, 39 | "dependencies": { 40 | "express": "~5.0.0", 41 | "debug": "~2.0.0", 42 | "jade": "~1.6.0" 43 | }, 44 | "devDependencies": { 45 | "grunt" : "~0.5.1" 46 | } 47 | } -------------------------------------------------------------------------------- /chapter10/UDPError/ch10.udp_error_server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.udp_error_server.js 5 | */ 6 | console.info("------ UDP Error ------"); 7 | console.info(); 8 | var dgram = require('dgram'); // TODO: 引入网络(UDP)模块 9 | var HOST = '127.0.0.abc'; // TODO: 定义服务器地址 10 | var PORT = 12345; // TODO: 定义端口号 11 | /** 12 | * 创建UDP服务器 13 | */ 14 | console.info('Now create UDO Server...'); 15 | console.info(); 16 | /** 17 | * 使用dgram.createSocket()函数方法创建一个UPD服务器 18 | */ 19 | var server = dgram.createSocket('udp4'); 20 | /** 21 | * 为UDP服务器添加一个"listening"事件处理函数 22 | */ 23 | server.on('listening', function () { 24 | var address = server.address(); 25 | console.log('UDP Server listening on ' + address.address + ":" + address.port); 26 | console.info(); 27 | }); 28 | /** 29 | * 为UDP服务器添加一个"error"事件处理函数 30 | */ 31 | server.on('error', function(err) { 32 | console.log("server error:\n" + err.stack); 33 | server.close(); 34 | }); 35 | /** 36 | * 为UDP服务器添加一个"close"事件处理函数 37 | */ 38 | server.on('close', function() { 39 | console.log('server closed'); 40 | console.info(); 41 | }); 42 | /** 43 | * 为UDP服务器绑定主机和端口 44 | */ 45 | server.bind(PORT, HOST); -------------------------------------------------------------------------------- /chapter01/ch01.console-hanoi.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-23. 3 | * 4 | * ch01.console-hanoi.js 5 | */ 6 | var iCount = 0; //TODO: 定义移动次数 7 | var strMoveStep = ""; // TODO: 保存移动步骤 8 | console.info(); 9 | var readline = require('readline'); 10 | var rl = readline.createInterface({ 11 | input: process.stdin, 12 | output: process.stdout 13 | }); 14 | rl.question("请输入汉诺塔问题的圆盘数目:\t", function(count) { 15 | // TODO: print user input 16 | console.log("输入汉诺塔问题的圆盘数目为:\n", count); 17 | hanoi(count, "A", "B", "C"); 18 | console.info("移动步骤如下:\t%s", strMoveStep); 19 | console.info("移动次数为:\t%s", iCount); 20 | console.info(); 21 | rl.close(); 22 | }); 23 | /** 24 | * 移动圆盘的方法 25 | * @param x 26 | * @param y 27 | */ 28 | function move(x, y) { 29 | iCount++; 30 | //console.info("%s->%s", x, y); 31 | strMoveStep += x + "->" + y + "\t"; 32 | } 33 | /** 34 | * 完成汉诺塔问题的递归方法 35 | * @param m 36 | * @param a 37 | * @param b 38 | * @param c 39 | */ 40 | function hanoi(m, a, b, c) { 41 | if(m == 1) 42 | { 43 | move(a, c); 44 | } 45 | else 46 | { 47 | hanoi(m-1, a, c, b); 48 | move(a, c); 49 | hanoi(m-1, b, a ,c); 50 | } 51 | } -------------------------------------------------------------------------------- /chapter03/ch03.async-queue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-queue.js 5 | */ 6 | console.info('------ Node.js异步编程: Async queue ------'); 7 | console.info(); 8 | var async = require('async'); 9 | /** 10 | * 定义一个queue,设worker数量为2 11 | */ 12 | var q = async.queue(function(task, callback) { 13 | console.log('worker is processing task: ', task.name); 14 | callback(); 15 | }, 2); 16 | /** 17 | * 独立加入5个任务 18 | */ 19 | q.push({name: 'foo'}, function (err) { 20 | console.log('finished processing foo'); 21 | }); 22 | q.push({name: 'bar'}, function (err) { 23 | console.log('finished processing bar'); 24 | }); 25 | q.push({name: 'cap'}, function (err) { 26 | console.log('finished processing cap'); 27 | }); 28 | q.push({name: 'egg'}, function (err) { 29 | console.log('finished processing egg'); 30 | }); 31 | q.push({name: 'app'}, function (err) { 32 | console.log('finished processing app'); 33 | }); 34 | /** 35 | * listen:当最后一个任务交给worker时,将调用该函数 36 | */ 37 | q.empty = function() { 38 | console.log('no more tasks wating'); 39 | } 40 | /** 41 | * listen:当所有任务都执行完以后,将调用该函数 42 | */ 43 | q.drain = function() { 44 | console.log('all tasks have been processed'); 45 | } -------------------------------------------------------------------------------- /chapter10/UDPBroadcast/ch10.udp_broadcast_client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-5-18. 3 | * 4 | * ch10.udp_broadcast_client.js 5 | */ 6 | console.info("------ UDP broadcast ------"); 7 | console.info(); 8 | var dgram = require('dgram'); // TODO: 引入网络(UDP)模块 9 | var HOST = '255.255.255.255'; // TODO: 定义服务器地址 10 | var PORT = 12345; // TODO: 定义端口号 11 | var message = new Buffer('UDP Client to Server : Hello Server!'); 12 | /** 13 | * 创建UDP客户端 14 | */ 15 | console.info('Now create UDO Client...'); 16 | console.info(); 17 | /** 18 | * 使用dgram.createSocket函数方法创建一个UDP客户端 19 | */ 20 | var client = dgram.createSocket('udp4'); 21 | /** 22 | * 绑定套接字方法函数 23 | */ 24 | client.bind(function () { 25 | client.setBroadcast(true); 26 | }); 27 | /** 28 | * 向服务器发送UDP数据报 29 | */ 30 | client.send(message, 0, message.length, PORT, HOST, function(err, bytes) { 31 | if (err) throw err; 32 | console.log('UDP message sent to ' + HOST +':'+ PORT); 33 | console.info(); 34 | console.info(bytes); 35 | console.info(); 36 | client.close(); 37 | }); 38 | /** 39 | * 为UDP客户端添加一个"close"事件处理函数 40 | */ 41 | client.on('close', function() { 42 | console.log('client disconnected'); 43 | console.info(); 44 | }); -------------------------------------------------------------------------------- /chapter03/ch03.async-iterator.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/2/25. 3 | * 4 | * ch03.async-iterator.js 5 | */ 6 | var async = require('async'); 7 | var iter = async.iterator([ 8 | function() { console.log('111') }, 9 | function() { console.log('222') }, 10 | function() { console.log('333') } 11 | ]); 12 | iter(); 13 | 14 | //iterator(tasks) 15 | 将一组函数包装成为一个iterator,可通过next()得到以下一个函数为起点的新的iterator。该函数通常由async在内部使用,但如果需要时,也可在我们的代码中使用它。 16 | 17 | var iter = async.iterator([ 18 | function() { console.log('111') }, 19 | function() { console.log('222') }, 20 | function() { console.log('333') } 21 | ]); 22 | iter(); 23 | /* 24 | 直接调用(),会执行当前函数,并返回一个由下个函数为起点的新的iterator。调用next(),不会执行当前函数,直接返回由下个函数为起点的新iterator。 25 | 26 | 对于同一个iterator,多次调用next(),不会影响自己。如果只剩下一个元素,调用next()会返回null。 27 | 28 | 通过next函数获得新的iter,并调用它,看看输出结果。 29 | 30 | 想一想哪些场景可以用到iterator呢。 31 | 32 | 课程小结 33 | async模块在流程控制方面给我们带来了比较全面的解决办法,下面我们来回顾一下都有哪几种方案: 34 | 35 | 串行控制: 36 | series、waterfall、compose; 37 | 38 | 并行控制: 39 | parallel、parallelLimit、queue; 40 | 41 | 循环控制: 42 | whilst、doWhilst、until、doUntil、forever; 43 | 44 | 其他控制: 45 | apply‘applyEach、iterator、auto; 46 | 47 | 学习了async模块后,对一般的函数嵌套问题都能够引刃而解,如果还有比较特别的应用需求,可以跟大家一起讨论一下,看看小伙伴有没有更好的解决办法,欢迎继续学习其他课程。 48 | */ -------------------------------------------------------------------------------- /Chapter14/ch14.mysql_conn.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-25. 3 | * 4 | * ch14.mysql_conn.js 5 | */ 6 | console.info("------ mysql connnection() ------"); 7 | console.info(); 8 | var http = require("http"); // TODO: 引入HTTP模块 9 | var mysql = require('/usr/local/lib/node_modules/mysql'); // TODO: 引入mysql模块 10 | console.log("Now start HTTP server on port 6868..."); 11 | console.info(); 12 | /** 13 | * 创建数据库连接 14 | */ 15 | var connection = mysql.createConnection({ 16 | host: "localhost", // TODO: 主机地址 17 | user: "root", // TODO: 数据库用户名 18 | password: "root", // TODO: 数据库密码 19 | database: "nodejs", // TODO: 数据库名称 20 | port: 3306 // TODO: 端口号 21 | }); 22 | /** 23 | * 创建HTTP服务器 24 | */ 25 | http.createServer(function (req, res) { 26 | res.writeHead(200, { "Content-Type" : "text/html;charset=utf8" }); 27 | res.write("

测试 Node.js - MySQL 数据库连接!


"); 28 | /** 29 | * 测试数据库连接 30 | */ 31 | connection.connect(function(err) { 32 | if(err) { 33 | res.end('

Error Connected to MySQL!

'); 34 | return; 35 | } else { 36 | res.end('

Connected to MySQL!

'); 37 | } 38 | }); 39 | }).listen(6868); // TODO: 监听6868端口号 40 | -------------------------------------------------------------------------------- /chapter02/ch02.module-load-counter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-2-12. 3 | */ 4 | /* 5 | 一个Node.js文件就是一个模块,这个文件可能是Javascript代码、JSON或者编译过的C/C++扩展。 6 | 重要的两个对象: 7 | require是从外部获取模块 8 | exports是把模块接口公开 9 | */ 10 | var counter = require('./1_modules_custom_counter'); 11 | console.log('第一次调用模块[1_modules_custom_counter]'); 12 | counter.seOutputVal(10); //设置从10开始计数 13 | counter.setIncrement (10); //设置增量为10 14 | counter.printNextCount(); 15 | counter.printNextCount(); 16 | counter.printNextCount(); 17 | counter.printNextCount(); 18 | /* 19 | require多次调用同一模块不会重复加载 20 | */ 21 | var counter = require('./1_modules_custom_counter'); 22 | console.log('第二次调用模块[1_modules_custom_counter]'); 23 | counter.printNextCount(); 24 | 25 | 运行可以发现通过exports和module.exports对外公开的方法都可以访问! 26 | 27 | 示例中可以看到,我两次通过require('./1_modules_custom_counter')获取模块,但是第二次引用后调用printNextCount()方法确从60开始~~~ 28 | 29 | 原因是node.js通过requirerequire多次调用同一模块不会重复加载,Node.js会根据文件名缓存所有加载过的文件模块,所以不会重新加载了 30 | 31 | 注意:通过文件名缓存是指实际文件名,并不会因为传入的路径形式不一样而认会是不同的文件 32 | 33 | 在我创建的1_modules_custom_counter文件中有一个printOutputVal()方法,它并没有通过exports或module.exports提供对外公开访问方法, 34 | 35 | 如果1_modules_load文件中直接访问运行会出现什么样的情况呢? 36 | 37 | 答案是:TypeError: Object # has no method 'printOutputVal' 38 | -------------------------------------------------------------------------------- /Chapter12/requestbasic/ch12.http_request_basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-16. 3 | * 4 | * ch12.http_request_basic.js 5 | */ 6 | console.info("------ http - create basic client ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 定义服务器参数字段 11 | * @type {{hostname: string, port: number, path: string, method: string}} 12 | */ 13 | var options = { 14 | hostname: 'localhost', // TODO: 定义服务器主机地址 15 | port: 6868, // TODO: 定义服务器主机端口号 16 | path: '/', // TODO: 定义服务器路径 17 | method: 'POST' // TODO: 定义服务器访问方式i 18 | }; 19 | /** 20 | * 通过http.request()函数方法 21 | * 由客户端向HTTP服务器发起请求 22 | */ 23 | var req = http.request(options, function(res) { 24 | console.log('STATUS: ' + res.statusCode); 25 | console.log('HEADERS: ' + JSON.stringify(res.headers)); 26 | res.setEncoding('utf8'); 27 | res.on('data', function (chunk) { 28 | console.log('BODY: ' + chunk); 29 | }); 30 | }); 31 | /** 32 | * 监听request对象的'error'事件 33 | */ 34 | req.on('error', function(e) { 35 | console.log('problem with request: ' + e.message); 36 | }); 37 | /** 38 | * write data to request body 39 | */ 40 | req.write('data\n'); 41 | /** 42 | * write end to request body 43 | */ 44 | req.end(); -------------------------------------------------------------------------------- /chapter08/ch08.fs_truncateSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-20. 3 | * 4 | * ch08.fs_truncateSync.js 5 | */ 6 | console.info("------ fs truncateSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var exec = require('child_process').exec; // TODO: 引入child_process模块 10 | var child_pre = exec('cat txt/truncateSync.txt', 11 | function (error, stdout, stderr) { 12 | console.info('cat txt/truncateSync.txt stdout: '); 13 | console.log(stdout); // TODO: 打印输出 stdout 14 | console.log('length: ' + stdout.length); // TODO: 输出数据长度 15 | console.log(stderr); // TODO: 打印输出 stderr 16 | console.info(); 17 | fs.truncateSync('txt/truncateSync.txt', 6); // TODO: 修改文件内容长度(同步方法) 18 | console.log('fs.truncateSync() Done'); 19 | var child_suf = exec('cat txt/truncateSync.txt', 20 | function (error, stdout, stderr) { 21 | console.info('cat txt/truncateSync.txt stdout: '); 22 | console.log(stdout); // TODO: 打印输出 stdout 23 | console.log('length: ' + stdout.length); // TODO: 输出数据长度 24 | console.log(stderr); // TODO: 打印输出 stdout 25 | console.info(); 26 | }); 27 | }); 28 | console.info(); -------------------------------------------------------------------------------- /Chapter12/writeheader/ch12.http_request_writeheader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-16. 3 | * 4 | * ch12.http_request_writeheader.js 5 | */ 6 | console.info("------ http - client write header ------"); 7 | console.info(); 8 | var http = require('http'); // TODO: 引入http模块 9 | /** 10 | * 定义服务器参数字段 11 | * @type {{hostname: string, port: number, path: string, method: string}} 12 | */ 13 | var options = { 14 | hostname: 'localhost', // TODO: 定义服务器主机地址 15 | port: 6868, // TODO: 定义服务器主机端口号 16 | path: '/', // TODO: 定义服务器路径 17 | method: 'POST' // TODO: 定义服务器访问方式i 18 | }; 19 | /** 20 | * 通过http.request()函数方法 21 | * 由客户端向HTTP服务器发起请求 22 | */ 23 | var req = http.request(options, function(res) { 24 | console.log('STATUS: ' + res.statusCode); 25 | console.log('HEADERS: ' + JSON.stringify(res.headers)); 26 | res.setEncoding('utf8'); 27 | res.on('data', function (chunk) { 28 | console.log('BODY: ' + chunk); 29 | }); 30 | }); 31 | /** 32 | * 监听request对象的'error'事件 33 | */ 34 | req.on('error', function(e) { 35 | console.log('problem with request: ' + e.message); 36 | }); 37 | /** 38 | * write data to request body 39 | */ 40 | req.write('data\n'); 41 | /** 42 | * write end to request body 43 | */ 44 | req.end(); -------------------------------------------------------------------------------- /Chapter11/ch11.stream_readable_basic.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-6-3. 3 | * 4 | * ch11.stream_readable_basic.js 5 | */ 6 | console.info("------ stream createReadStream() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | /** 10 | * 调用文件系统(fs)模块的createReadStream()方法创建可读(Readable)流 11 | */ 12 | var rs = fs.createReadStream('data/basic.txt'); 13 | /** 14 | * 调用readable.setEncoding()函数方法设置编码 15 | */ 16 | rs.setEncoding('utf8'); 17 | /** 18 | * 流(Stream)模块 --- 'readable'事件处理函数 19 | */ 20 | rs.on('readable', function() { 21 | console.log('readable event emitted.'); 22 | console.info(); 23 | }); 24 | /** 25 | * 流(Stream)模块 --- 'data'事件处理函数 26 | */ 27 | rs.on('data', function (chunk) { 28 | console.log('data event emitted.'); 29 | console.info(); 30 | }); 31 | /** 32 | * 流(Stream)模块 --- 'error'事件处理函数 33 | */ 34 | rs.on('error', function () { 35 | console.log('error event emitted.'); 36 | console.info(); 37 | }); 38 | /** 39 | * 流(Stream)模块 --- 'end'事件处理函数 40 | */ 41 | rs.on('end', function () { 42 | console.log('end event emitted.'); 43 | console.info(); 44 | }); 45 | /** 46 | * 流(Stream)模块 --- 'close'事件处理函数 47 | */ 48 | rs.on('close', function () { 49 | console.log('close event emitted.'); 50 | console.info(); 51 | }); -------------------------------------------------------------------------------- /chapter08/ch08.fs_ftruncateSync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by king on 15-4-20. 3 | * 4 | * ch08.fs_ftruncateSync.js 5 | */ 6 | console.info("------ fs ftruncateSync() ------"); 7 | console.info(); 8 | var fs = require('fs'); // TODO: 引入文件系统模块 9 | var exec = require('child_process').exec; // TODO: 引入child_process模块 10 | var child_pre = exec('cat txt/ftruncateSync.txt', 11 | function (error, stdout, stderr) { 12 | console.info('cat txt/ftruncateSync.txt stdout: '); 13 | console.log(stdout); // TODO: 打印输出 stdout 14 | console.log(stderr); // TODO: 打印输出 stderr 15 | var fd = fs.openSync('txt/ftruncateSync.txt', 'a'); // TODO: 打开文件(同步方式) 16 | fs.ftruncateSync(fd, 10); // TODO: 文件内容截取 17 | console.info("文件描述符: " + fd); // TODO: 打印输出文件描述符 18 | console.info(); 19 | console.log('fs.ftruncateSync() Done'); 20 | fs.closeSync(fd); // TODO: 关闭文件(同步方式) 21 | var child_suf = exec('cat txt/ftruncateSync.txt', 22 | function (error, stdout, stderr) { 23 | console.info('cat txt/ftruncateSync.txt stdout: '); 24 | console.log(stdout); // TODO: 打印输出 stdout 25 | console.log(stderr); // TODO: 打印输出 stdout 26 | }); 27 | console.info(); 28 | }); 29 | console.info(); -------------------------------------------------------------------------------- /chapter04/ch04.buffer-define.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by KING on 2015/3/14. 3 | * 4 | * ch04.buffer-define.js 5 | */ 6 | // TODO: 定义并初始化Buffer对象 --- buffer16 7 | var buffer16 = new Buffer([0x6e, 0x6f, 0x64, 0x65, 0x6a, 0x73]); // TODO: 数组形式 8 | console.log("The variable buffer16's length is " + buffer16.length + "."); 9 | console.log("The variable buffer16 is " + buffer16 + "."); 10 | // TODO: 使用数组下标形式读取Buffer对象 11 | for(var i=0; i