[关闭]
@mSolo 2015-05-10T07:29:27.000000Z 字数 16610 阅读 2960

MEAN 全栈工程师手札(二):启程

JavaScript NodeJS


背景知识

script元素

命名

文件 filenameslikethis.js foo.namespaceNamesLikeThis.bar
类名 ClassNamesLikeThis 方法 methodNamesLikeThis
函数 functionNamesLikeThis 常量 CONSTANT_VALUES_LIKE_THIS
枚举 EnumNamesLikeThis 变量 variableNamesLikeThis

Google 规范

JavaScript 必知必会

垃圾收集

引用类型

Object 类型

Array 类型

  1. var colors = [“red”, blue”, green”];
  2. colors[99] = black”; // 在位置 99 插入 "black"
  3. alert(colors.length); // 长度变为 100 了

Date 类型

RegExp 类型

Function 类型

  1. function callSomeFunction(someFunction, someArgument){
  2. return someFunction(someArgument);
  3. }
  4. function add10(num){
  5. return num + 10;
  6. }
  7. var result1 = callSomeFunction(add10, 10);
  8. alert(result1); //20
  1. function sum(num1, num2){
  2. return num1 + num2;
  3. }
  4. function callSum1(num1, num2){
  5. return sum.apply(this, arguments); //passing in arguments object
  6. }
  7. function callSum2(num1, num2){
  8. return sum.apply(this, [num1, num2]); //passing in array
  9. }
  10. alert(callSum1(10,10)); //20
  11. alert(callSum2(10,10)); //20
  1. function sum(num1, num2){
  2. return num1 + num2;
  3. }
  4. function callSum(num1, num2){
  5. return sum.call(this, num1, num2);
  6. }
  7. alert(callSum(10,10)); //20
  1. window.color = red”;
  2. var o = { color: blue };
  3. function sayColor(){
  4. alert(this.color);
  5. }
  6. sayColor(); //red
  7. sayColor.call(this); //red
  8. sayColor.call(window); //red
  9. sayColor.call(o); //blue
  1. window.color = red”;
  2. var o = { color: blue };
  3. function sayColor(){
  4. alert(this.color);
  5. }
  6. var objectSayColor = sayColor.bind(o);
  7. objectSayColor(); //blue

命名空间

  1. var com = com || {};
  2. com.apress = com.apress || {};
  3. com.apress.chapterone = com.apress.chapterone || {};
  4. com.apress.chapterone.sectionObject = { ... };
  5. var MYAPP = {}; // the container for your application
  6. MYAPP.stooge = {
  7. "first-name": "Joe",
  8. "last-name": "Howard"
  9. };
  10. MYAPP.flight = {
  11. airline: "Oceanic",
  12. number: 815,
  13. departure: {
  14. IATA: "SYD",
  15. time: "2004-09-22 14:55",
  16. city: "Sydney"
  17. },
  18. arrival: {
  19. IATA: "LAX",
  20. time: "2004-09-23 10:42",
  21. city: "Los Angeles"
  22. }
  23. };

创建对象的方法

工厂模式

  1. function createPerson(name, age, job) {
  2. var o = new Object();
  3. // ...
  4. return o;
  5. }

构造函数模式

  1. function Person(name, age, job) {
  2. this.name = name;
  3. // ...
  4. this.sayName = function() { alert(this.name); };
  5. }
  6. var person1 = new Person("Nicholas", 29, "Software Engineer");

原型模式(in 操作符)

  1. // Define a constructor called Accommodation
  2. function Accommodation() {}
  3. // Assign properties and methods to our "class" blueprint with an object literal
  4. Accommodation.prototype = {
  5. floors: 0,
  6. rooms: 0,
  7. sharedEntrance: false,
  8. lock: function() {},
  9. unlock: function() {}
  10. };

组合使用构造函数模式和原型模式

  1. function Person(name, age, job){
  2. this.name = name;
  3. this.age = age;
  4. this.job = job;
  5. this.friends = [“Shelby”, Court”];
  6. }
  7. Person.prototype = {
  8. constructor: Person,
  9. sayName : function () {
  10. alert(this.name);
  11. }
  12. };

动态原型模式

  1. function Person(name, age, job){
  2. this.name = name;
  3. this.age = age;
  4. this.job = job;
  5. //methods
  6. if (typeof this.sayName != function”){
  7. Person.prototype.sayName = function(){
  8. alert(this.name);
  9. };
  10. }
  11. }

寄生构造函数模式

  1. function SpecialArray(){
  2. //create the array
  3. var values = new Array();
  4. //add the values
  5. values.push.apply(values, arguments);
  6. //assign the method
  7. values.toPipedString = function(){
  8. return this.join(“|”);
  9. };
  10. return values;
  11. }
  12. var colors = new SpecialArray(“red”, blue”, green”);
  13. alert(colors.toPipedString()); //”red|blue|green”

稳妥构造函数模式

  1. function Person(name, age, job){
  2. //create the object to return
  3. var o = new Object();
  4. //optional: define private variables/functions here
  5. o.sayName = function(){
  6. alert(name);
  7. };
  8. return o;
  9. }

解析对象

  1. var Person = {
  2. name: "Nicholas",
  3. age: 29,
  4. job: "Software Engineer",
  5. sayName: function(){
  6. alert(this.name);
  7. }
  8. };
  9. var person1 = new Person();
  10. var person2 = new Person();
person1.name = "Greg";
  1. function Person(){}
  2. var friend = new Person();
  3. Person.prototype = {
  4. constructor: Person,
  5. name : "Nicholas",
  6. age : 29,
  7. job : "Software Engineer",
  8. sayName : function () {
  9. alert(this.name);
  10. }
  11. };
friend.sayName(); //error

属性管理器

  1. var car = {};
  2. Object.defineProperty(car, 'doors', {
  3. configurable: true,
  4. value: 4
  5. });
  6. Object.defineProperty(car, 'wheels', {
  7. configurable: false,
  8. value: 4
  9. });
  10. delete car.doors;
  11. console.log(car.doors); // => "undefined"
  12. delete car.wheels;
  13. console.log(car.wheels); // => "4"
  1. Object.defineProperty(car, 'doors', {
  2. writable: true,
  3. configurable: true,
  4. enumerable: true,
  5. value: 4
  6. });
  7. Object.defineProperty(car, 'wheels', {
  8. writable: true,
  9. configurable: true,
  10. enumerable: true,
  11. value: 4
  12. });
  13. Object.defineProperty(car, 'trackingEnabled', {
  14. enumerable: false,
  15. value: true
  16. });
  17. for (var x in car) { // same as console.log(Object.keys(car));
  18. console.log(x); // output: ['doors', 'wheels']
  19. }
  20. // => ["doors", "wheels", "trackingEnabled"]
  21. console.log(Object.getOwnPropertyNames(car));
  22. console.log(car.propertyIsEnumerable('trackingEnabled')); //false
  23. console.log(car.trackingEnabled); //true
  1. Object.defineProperty(car, 'wheels', {
  2. value: 4,
  3. writable: false
  4. });
  5. car.wheels = 5;
  6. console.log(car.wheels); // => 4
  1. ({
  2. maxwidth: 600,
  3. maxheight: 400,
  4. gimmeMax: function () {
  5. return this.maxwidth + "x" + this.maxheight;
  6. },
  7. init: function () {
  8. console.log(this.gimmeMax());
  9. }
  10. }).init();

继承

原型链

  1. function SuperType(){
  2. this.colors = [“red”, blue”, green”];
  3. }
  4. function SubType(){}
  5. //inherit from SuperType
  6. SubType.prototype = new SuperType();
  7. var instance1 = new SubType();
  8. instance1.colors.push(“black”);
  9. alert(instance1.colors); //”red,blue,green,black”
  10. var instance2 = new SubType();
  11. alert(instance2.colors); //”red,blue,green,black”

借用构造函数(伪造对象或经典继承)

  1. function SuperType() {
  2. this.colors = [“red”, blue”, green”];
  3. }
  4. function SubType(){ //inherit from SuperType
  5. SuperType.call(this);
  6. }
  7. var instance1 = new SubType();
  8. instance1.colors.push(“black”);
  9. alert(instance1.colors); //”red,blue,green,black”
  10. var instance2 = new SubType();
  11. alert(instance2.colors); //”red,blue,green”

组合继承

  1. function SuperType() {
  2. this.name = name;
  3. this.colors = [“red”, blue”, green”];
  4. }
  5. SuperType.prototype.sayName = function(){
  6. alert(this.name);
  7. };
  8. function SubType(name, age){
  9. SuperType.call(this, name);
  10. this.age = age;
  11. }
  12. SubType.prototype = new SuperType();
  13. SubType.prototype.constructor = SubType;
  14. SubType.prototype.sayAge = function(){
  15. alert(this.age);
  16. };
  17. var instance1 = new SubType(“Nicholas”, 29);
  18. instance1.colors.push(“black”);
  19. alert(instance1.colors); //”red,blue,green,black”
  20. instance1.sayName(); //”Nicholas”;
  21. instance1.sayAge(); //29
  22. var instance2 = new SubType(“Greg”, 27);
  23. alert(instance2.colors); //”red,blue,green”
  24. instance2.sayName(); //”Greg”;
  25. instance2.sayAge(); //27

原型式继承

  1. function object(o){
  2. function F(){}
  3. F.prototype = o;
  4. return new F();
  5. }
  6. var person = {
  7. name: Nicholas”,
  8. friends: [“Shelby”, Court”, Van”]
  9. };
  10. var anotherPerson = object(person);
  11. anotherPerson.name = Greg”;
  12. anotherPerson.friends.push(“Rob”);
  13. var yetAnotherPerson = object(person);
  14. yetAnotherPerson.name = Linda”;
  15. yetAnotherPerson.friends.push(“Barbie”);
  16. alert(person.friends); //”Shelby,Court,Van,Rob,Barbie”
  1. var person = {
  2. name: Nicholas”,
  3. friends: [“Shelby”, Court”, Van”]
  4. };
  5. var anotherPerson = Object.create(person, {
  6. name: {
  7. value: Greg
  8. }
  9. });
  10. alert(anotherPerson.name); //”Greg”

寄生式继承

  1. function createAnother(original){
  2. var clone = object(original); //create a new object by calling a function
  3. clone.sayHi = function(){ //augment the object in some way
  4. alert(“hi”);
  5. };
  6. return clone; //return the object
  7. }
  8. var person = {
  9. name: Nicholas”,
  10. friends: [“Shelby”, Court”, Van”]
  11. };
  12. var anotherPerson = createAnother(person);
  13. anotherPerson.sayHi(); //”hi”

寄生组合式继承

  1. function inheritPrototype(subType, superType){
  2. var prototype = object(superType.prototype); //create object
  3. prototype.constructor = subType; //augment object
  4. subType.prototype = prototype; //assign object
  5. }
  6. function SuperType(name){
  7. this.name = name;
  8. this.colors = [“red”, blue”, green”];
  9. }
  10. SuperType.prototype.sayName = function(){
  11. alert(this.name);
  12. };
  13. function SubType(name, age){
  14. SuperType.call(this, name);
  15. this.age = age;
  16. }
  17. inheritPrototype(SubType, SuperType);
  18. SubType.prototype.sayAge = function(){
  19. alert(this.age);
  20. };

NodeJS 入门

创建项目

  1. mkdir first-project
  2. cd first-project
  3. npm init

必备的包

  1. npm install -g grunt grunt-cli
  2. npm install -g request
  3. npm install -g express
  4. npm install -g nodemon # restart the server when the source code change
  5. npm install -g bower, bower install # for jquery, bootstrap, etc.
  6. npm install -g passport passport-google
  7. npm install -g async tamejs
  8. npm install -g mongoose mysql redis

NodeJS 事件处理流程示例

NodeJS Module

理解 CommonJS Modules

What CommonJS actually represents is a set of specification proposals that will aim to create a standardized system of module loaders.

Module Sample

  1. function ABC () {
  2. this.varA = 10;
  3. this.varB = 20;
  4. this.functionA = function (var1, var2) {
  5. console.log(var1 + " " + var2);
  6. }
  7. }
  8. module.exports = ABC;
  9. var ABCClass = require('./abc');
  10. var obj = new ABCClass();
  11. obj.functionA(1, 2); // ouput: 1 2
  1. function printA() {
  2. console.log('A');
  3. }
  4. function printB() {
  5. console.log('B');
  6. }
  7. function printC() {
  8. console.log('C');
  9. }
  10. module.exports.printA = printA;
  11. module.exports.printB = printB;
  12. module.exports.pi = Math.PI;
  13. var utilTool = require('./utiltool');
  14. utilTool.printA(); // -> A
  15. utilTool.printB(); // -> B
  16. console.log(utilTool.pi); // -> 3.1415
  1. delete require.cache[require.resolve('./myclass')];
  1. // group/index.js
  2. module.exports = {
  3. one: require('./one'),
  4. two: require('./two')
  5. };
  6. // group/one.js
  7. module.exports = function() {
  8. console.log('one');
  9. };
  10. // index.js
  11. var group = require('./group');
  12. group.one();
  13. group.two();

NodeJS 核心模块

基本工具模块

NodeJS 基本示例

命令行

  1. const fs = require('fs')
  2. , filename = process.argv[2];
  3. if (!filename) {
  4. throw Error("A file to watch must be specified!");
  5. }
  6. fs.watch(filename, function() {
  7. console.log("File " + filename + " just changed!");
  8. });
  9. console.log("Now watching " + filename + " for changes...");
  1. var child_process = require('child_process');
  2. var exec = child_process.exec;
  3. exec('ls', function(err, stdout, stderr) {
  4. // ...
  5. });
  6. var spawn = require('child_process').spawn;
  7. var child = spawn('tail', ['-f', '/var/log/system.log']);
  8. child.stdout.on('data', function(data) {
  9. console.log('tail output: ' + data);
  10. });
  11. child.stderr.on('data', function(data) {
  12. console.log('tail error output:', data);
  13. });

读写

  1. var fs = require('fs');
  2. var path = require('path');
  3. fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
  4. if (err) throw err;
  5. console.log(data);
  6. });
  7. const fs = require('fs'),
  8. data = fs.readFileSync('target.txt'); // data = fs.readFileSync('target.txt', 'utf8');
  9. process.stdout.write(data.toString());
  1. var fs = require('fs');
  2. fs.writeFile('message.txt', 'Hello World!', function (err) {
  3. if (err) throw err;
  4. console.log('Writing is done.');
  5. });
  6. try {
  7. fs.writeFileSync('./doesnotexist/newfile.txt', 'content');
  8. } catch(err) {
  9. console.log('unable to create a file in a non existent sub directory');
  10. console.log(err);
  11. }
  12. fs.appendFile('write.txt', 'More content', function(err) {
  13. if (err) {
  14. throw err;
  15. }
  16. console.log('appended');
  17. });
  1. var fs = require('fs');
  2. fs.createReadStream('./data/customers.csv').pipe(process.stdout);

使用 Events

  1. var events = require('events')
  2. , emitter = new events.EventEmitter();
  3. function doATask(status) {
  4. if (status === 'success') {
  5. emitter.emit('taskSuccess'); // Specific event
  6. } else if (status === 'fail') {
  7. emitter.emit('taskFail');
  8. }
  9. emitter.emit('taskComplete', 'complete', status);
  10. }
  11. emitter.on('taskSuccess', function() {
  12. console.log('task success!');
  13. });
  14. emitter.on('taskFail', function() {
  15. console.log('task fail');
  16. });
  17. emitter.on('taskComplete', function(type, status) {
  18. console.log('the task is ', type, ' with status ', status);
  19. });
  20. setTimeout(doATask, 500, 'success');
  21. setTimeout(doATask, 1000, 'fail');
  22. // output:
  23. a new listener was added
  24. a new listener was added
  25. a new listener was added
  26. task success
  27. the task is complete with status success
  28. task fail
  29. the task is complete with status fail

有用的代码片段

  1. console.log('__dirname:', __dirname);
  2. console.log('__filename:', __filename);
  3. console.time('read'); // Benchmarking
  4. console.timeEnd('read');

NodeJS TCP

  1. const
  2. fs = require('fs'),
  3. net = require('net'),
  4. filename = process.argv[2],
  5. server = net.createServer(function(connection) {
  6. console.log('Subscriber connected.');
  7. connection.write("Now watching '" + filename + "' for changes...\n");
  8. // watcher setup
  9. let watcher = fs.watch(filename, function() {
  10. connection.write("File '" + filename + "' changed: " + Date.now() + "\n");
  11. });
  12. // cleanup
  13. connection.on('close', function() {
  14. console.log('Subscriber disconnected.');
  15. watcher.close();
  16. });
  17. });
  18. if (!filename) {
  19. throw Error('No target filename was specified.');
  20. }
  21. server.listen(5432, function() {
  22. console.log('Listening for subscribers...');
  23. });
  1. $ node --harmony net-watcher.js target.txt
  2. Listening for subscribers...

Chat Room 示例

  1. # package.json
  2. {
  3. "name": "tcp-chat"
  4. , "description": "Our first TCP server"
  5. , "version": 0.0.1"
  6. }
  1. var net = require('net')
  2. var server = net.createServer(function (conn) {
  3. var count = 0
  4. , users = {}
  5. conn.setEncoding('utf8');
  6. var nickname;
  7. conn.write(
  8. '\n > welcome to \033[92mnode-chat\033[39m!'
  9. + '\n > ' + count + ' other people are connected at this time.'
  10. + '\n > please write your name and press enter: '
  11. );
  12. count++;
  13. conn.on('data', function (data) {
  14. broadcast('\033[90m > ' + nickname + ' joined the room\033[39m\n');
  15. // . . .
  16. broadcast('\033[96m > ' + nickname + ':\033[39m ' + data + '\n', true);
  17. });
  18. conn.on('close', function () {
  19. count--;
  20. broadcast('\033[90m > ' + nickname + ' left the room\033[39m\n');
  21. delete users[nickname];
  22. });
  23. function broadcast (msg, exceptMyself) {
  24. for (var i in users) {
  25. if (!exceptMyself || i != nickname) {
  26. users[i].write(msg);
  27. }
  28. }
  29. }
  30. });
  31. server.listen(3000, function () {
  32. console.log('\033[96m server listening on *:3000\033[39m');
  33. });

NodeJS HTTP

  1. var http = require('http');
  2. var urlOpts = {host: 'www.nodejs.org', path: '/', port: '80'};
  3. if (process.argv[2]) {
  4. if (!process.argv[2].match('http://')) {
  5. process.argv[2] = 'http://' + process.argv[2];
  6. }
  7. urlOpts = url.parse(process.argv[2]);
  8. }
  9. http.get(urlOpts, function (response) {
  10. response.on('data', function (chunk) {
  11. console.log(chunk.toString());
  12. });
  13. }).on('error', function (e) {
  14. console.log('error:' + e.message);
  15. });
  1. var http = require('http');
  2. var urlOpts = {
  3. host: 'market.finance.sina.com.cn',
  4. path: '/downxls.php?date=2014-07-11&symbol=sz002024',
  5. port: '80'
  6. };
  7. http.get(urlOpts, function (response) {
  8. response.on('data', function (chunk) {
  9. console.log(chunk.toString());
  10. });
  11. });
  1. var http = require('http');
  2. http.createServer(function (request, response) {
  3. response.writeHead(200, {'Content-Type': 'text/html'});
  4. response.end('Woohoo!');
  5. }).listen(8080);
  1. var http = require('http');
  2. var form = require('fs').readFileSync('form.html');
  3. http.createServer(function (request, response) {
  4. if (request.method === "POST") {
  5. var postData = '';
  6. request.on('data', function (chunk) {
  7. postData += chunk;
  8. }).on('end', function() {
  9. console.log('User Posted:\n' + postData);
  10. response.end('You Posted:\n' + postData);
  11. });
  12. }
  13. }).listen(8080);
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注