nodeJS rookie tutorial notes

http module

var http = require('http');                                     // 引入http模块
var url = require('url');                                       // 引入url模块
var querystring = require('querystring');                       // 引入查询字符串模块
http.createServer(function (request, response) {                // 创建http服务
    response.writeHead(200, {'Content-Type': 'text/plain'});    // 发送响应头部
    var parseObj = url.parse(req.url, true)                     // 解析URL(get请求)
    var parseObj = querystring.parse(body);                     // 解析URL参数(post请求)
    response.write("'<h4>Hello World</h4>\n'")                  // 发送响应主体
    response.end();                                             // 结束响应
})

events event module

var events = require('events');                         // 引入事件模块
var evEmit = new events.EventEmitter();                 // 创建事件对象

Examples of methods

evEmit.on("事件名", connectHandler(参数1,参数2...));    // 绑定事件
evEmit.once("事件名", connectHandler);                 // 单次绑定事件
evEmit.removeListener("事件名", connectHandler);       // 移除事件
evEmit.removeAllListeners(### event);                 // 移除所有事件     
evEmit.emit("事件名",参数1,参数2..);                    // 触发事件
evEmit.setMaxListeners(n);                            // 设置绑定默认数量
evEmit.listeners(### event);                          // 返回监听器(函数)数组

Modular approach

evEmit.listenerCount("事件名");      // 返回指定事件的监听器数量

event

evEmit.on("newListener", connectHandler(事件名称,回调));      

// 该事件在添加常规事件时触发

// newListener回调中任何额外的被注册到相同名称的监听器会在监听器被添加之前被插入
evEmit.on("error", connectHandler(错误对象));

// 如果EventEmitter没有为error事件注册至少一个监听器,当error事件触发时,会抛出错误、打印堆栈跟踪、且退出 Node.js 进程,因此最佳实践是应该始终为error事件注册监听器

Buffer Buffer

var buf = new Buffer(256);                    // 创建缓冲实例

Write buffer

buf.write("字符",起始索引,字节长度,编码类型)      // 返回buf实际能够写入的长度

Read buffer

buf.toString(编码类型,起始索引,结束位置)          // 返回解码字符串

Buffer转JSON

buf.toJSON()                                  // 返回json对象

Buffer Merge

Buffer.concat(buf数组,合并长度)                // 返回合并后的buf对象

Compare buffer

Buffer.compare(buf1,buf2)                    // 返回一个数字(buf1在buf2之前,之后或相同)
buf1.compare(buf2)                           // ...

Copy buffer

sourceBuf.copy(targetBuf,targetStart,sourceStart,sourceEnd)

// 无返回值
// sourceBuf-拷贝对象
// targetBuf-被拷贝对象

Crop Buffer

buf.slice(0,2)      // 返回一个新的缓冲区(它和旧缓冲区指向同一块内存)

Stream flow

Stream type

  • Readble => readable stream

  • Writable => writeable stream

  • Duplex => stream writable

  • Transform => modifications and variations can read and write data in the process stream (read and write)

Common events

  • data => is triggered when there is data read

  • end => no more data is read trigger

  • error => receiving an error occurs and the writing process to trigger

  • finish => triggered when all the data has been written to the underlying system

Read the stream data

var data = "";
var readerStream = fs.createReadStream('input.txt') // 创建可读流
readerStream.setEncoding('UTF8')                    // 设置编码
readerStream.on('data',function(chunk){             // 绑定data事件
    data += chunk;
})

Writing the stream

var data = '菜鸟教程官网地址:www.runoob.com';
var writerStream = fs.createWriteStream('output.txt');  // 创建可写流
writerStream.write(data,'UTF8');                        // 使用utf8编码写入数据
writerStream.end("字符数据",编码,回调函数);                // 声明文件结尾
writerStream.on('finish', function() {                  // 绑定finish事件
    console.log("写入完成。");
});

module module

require

  • "./" to the current directory

  • A Node is a module file (js file, json or compiled c / c ++ module)

exports

  • exports.A = ... the module A as the access interface, require the "Object interface" used in the form

  • module.exports = A to A's external module as a whole, can be used directly require

  • module.exports operation is unique, the latter overwrite the previous

require the search strategy

  • Cache file module => primary cache memory module => = native memory modules> file module

require acceptable parameters

  • http, fs, path, etc., native module

  • ../mod or ../mod, relative path file module

  • ./pathtomodule/mod, the absolute path of the file module

  • mod non-native module file module

commonjs specification

  • module.exports real interfaces, exports are only one of its aid

  • All exports to collect properties and methods, are assigned to the module.exports, eventually returned to the caller is module.exports rather than exports

  • If module.exports already has some of the properties and methods, then exports the information collected will be ignored

  • Your module can be any valid javascript object --boolean, number, date, JSON, string, function, array ...

node function

  • Use transfer functions and anonymous functions

node routing

  • It is present as a processing request module

  • Http create a service module, url resolution path module, the routing module is incorporated into implanted http module, and parses the path of the return value of the difference between the processing procedure

node global object

__filename

  • Represents the currently executing script file name, returns the absolute path where the script

  • If in the module, the module returns the file path

__dirname

  • Represents the directory where the currently executing script

process

  • It is used to describe the current state of the process Node.js object belongs to a global variable, i.e., the attribute global object

  • Common events

    • exit (triggered when the process is ready to quit)

    • beforeExit (triggered when a node empty event loop, and no other arrangements)

    • uncaughtException (an exception is triggered when the bubbling back to the event loop)

    • signal (when the process receives a signal to trigger)

util module

util.inherits

  • Implement prototype inheritance between objects

  • Parameters were (sub-function, the parent function)

util.inspect

  • To convert any object to a string method, typically used for debugging and error output

  • Accepts four parameters - (conversion target, whether to output hidden information, recursive hierarchy, the console output color)

util.isArray

util.isRegExp

util.isDate

util.isError

FileSystem module

Open the file asynchronously

fs.open(filePath,打开方式,权限,callback) 

// callback包含2个参数,分别为err对象,文件描述符(fd)

· Asynchronous get file information

fs.stat(filePath,callback)

// callback包含2个参数,分别为err对象和stats对象

// stats对象包含stats相关属性和方法,用于文件信息判断

· Asynchronous file write

fs.writeFile(file, data,options,callback)  // callback只包含err对象

· Read the file asynchronously

fs.readFile(file, option, callback)

// callback包含2个参数,分别为err对象和data文件

// 如果options是一个字符串,则它指定了字符编码

· Asynchronous read

fs.read(fd, buffer, offset, length, position, callback)

fd - fs.open()回调返回的文件描述符
buffer - 数据写入的缓冲区
offset - 缓冲区写入的写入偏移量
length - 要从文件中读取的字节数
position - 文件读取的起始位置,如果position的值为 null,则会从当前文件指针的位置读取
callback - 有三个参数err, bytesRead, buffer,err为错误信息,bytesRead表示读取的字节数,buffer为缓冲区对象

· Close the file asynchronously

fs.close(fd, callback)                // callback没有参数

• Intercept asynchronous file

fs.ftruncate(fd, len, callback)       // callback只包含err对象

· Asynchronous delete files

fs.unlink(path, callback)             // callback没有参数

· Create a directory asynchronous

fs.mkdir(path, 文件权限, callback)    // callback没有参数

· Asynchronous read directory

fs.readdir(path, 文件权限, callback)  // callback包含两个参数,分别为err对象和files列表

· Asynchronous delete the directory

fs.rmdir(path, callback)             // callback没有参数

express Framework

Request and response

  app.get('/', function (req, res) {})          // 处理请求和响应
  req.query                                     // 获取查询字符串
  res.send()                                    // 响应数据
  res.sendFile()                                // 响应文件(需要绝对路径,除非设置了根路径)
  res.end()                                     // 结束响应             
  var server = app.listen(8081,callback)       // 创建服务
  server.address()                              // 获取地址信息
  express.static(资源目录)                        // 托管静态资源
  var bodyParser = require('body-parser')
  bodyParser.urlencoded({ extended: false })    //创建application/x-www-form-urlencoded编码解析

routing

  • Who decided (designated script) to respond to client requests

RESTful API

  • A software design principles and style

  • web Services to meet the rest of this style (embodied http request service)

Multi-process node

  • Although the node is a single-threaded mode, but you can create multiple sub-processes on multi-core cpu system, which improves performance

  • Each child process always takes three stream objects

    • child.stdin-- standard input
    • child.stdout-- standard output
    • child.stderr-- standard error
  • node provides child_process module to create a child process, by:

    • exec-- use child process command, the output buffer of the child, returned as a callback function parameters
      • parameter:
        • command: The command to run, parameters separated by spaces
        • options: parameter object
        • callback: callback function (error, stdout, stderr)
    • spawn-- using the specified command-line parameters to create a new process
      • parameter:
        • command: Command to be run
        • args: an array of string parameters
        • options: parameter object
    • fork - a special form of spawn for modules running in the child process.
      • The method is different from the spawn, fork will be between parent process and the sub process to establish a communication pipe for communicating between processes
      • parameter:
        • Module to be run in a child process: modulePath
        • args: an array of string parameters
        • options: parameter object

mySQL

Connect to the database

    'SELECT 1 + 1 AS solution';

increase

'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';

delete

'DELETE FROM websites where id=6';

change

'UPDATE websites SET name = ?,url = ? WHERE Id = ?';

check

'SELECT * FROM websites';

mongoDB

Link Database

MongoDB会自动创建数据库和集合,使用前不需要手动去创建

increase

collection.insert(data,callback);

delete

collection.remove(whereStr,callback);

change

collection.update(whereStr,updateStr,callback);

check

collection.find(whereStr).toArray(callback);

Guess you like

Origin www.cnblogs.com/kanyu/p/12222306.html