【NodeJS】基础知识

nodejs基础

nodejs允许自己封装模块,使得编写程序可以模块化,便于维护整理。在一个js文件中写完封装的函数或对象后,可以使用exportsmodule.exports来将模块中的函数暴露给程序,使得整个程序可以使用,如:

function HelloWorld() {
    return 'Hello, node-js!';
}

module.exports.HelloWorld = HelloWorld;

要使用其他模块中的方法时,需要使用require来导入模块,如:

const http = require('http');
const helloWorld = require('./helloword');

再说回exportsmodule.exports,两者的功能相同,区别在于,exportsmodule.exports的缩略写法,如下写法是相同意思:

module.exports.HelloWorld = HelloWorld;
exports.HelloWorld = HelloWorld;

创建简单的nodejs服务器

nodejs封装由http模块实现服务器功能,只需引入使用即可,代码如下:

const http = require('http');
const helloWorld = require('./helloword');

var server = http.createServer(function(req, res) {
    if (req.method != 'GET') {
        res.statusCode = 404;
        res.end('Please Use GET method!');
    }
    else
        res.end(helloWorld.HelloWorld());
});

server.listen(30000);
console.log('Server is started on 30000 port……');

先导入http模块,然后使用createServer方法,在方法中传入回调函数来处理用户请求。
回调函数由两个参数reqres,代表着请求和响应。
req的属性有:req.methodreq.urlres可以使用setHeader('http响应头','参数')方法来设置响应头参数,使用res.statusCode = 200来设置响应状态码
在回调函数的最后,需要调用res.end()来结束回调函数的响应。

创建静态文件服务器

要搭建静态文件服务器,需要将引入nodejs自带的fs模块进行文件的读取,并将读取到的文件数据以数据流的形式传输到浏览器端,代码如下:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');

const root = __dirname;

var server = http.createServer(function(req, res) {
    var filePath = path.join(root, url.parse(req.url).pathname);
    var stream = fs.createReadStream(filePath);
    // stream.on('data', function(chunk) {
    //   res.write(chunk);  
    // })
    // stream.on('end', function() {
    //   res.statusCode = 200;
    //   res.end();  
    // })
    stream.pipe(res);
});

server.listen(3000);
console.log('Server is started on 3000 port……');

一步步来分析,__dirname为nodjs中的一个自带的属性变量,值为当前js文件所在的目录路径,在使用url模块的parse方法后,提取其中的pathname,使用path.join()方法将其组合成访问文件的绝对路径来对文件进行读取。不过这里需要一个异常处理,否则若访问文件不存在,没有异常处理则程序异常退出。

    stream.on('error', function(err){...})

使用fs.createReadStream()方法来创建读取文件数据流,这时有两种方法对文件数据进行读取:


    var stream = fs.createReadStream(filePath);
    // 1.
    stream.on('data', function(chunk) {
      res.write(chunk);  
    })
    stream.on('end', function() {
      res.statusCode = 200;
      res.end();  
    })

    // 2.
    stream.pipe(res);

第一种方法为设置事件监听器,写入回调函数,在on('data',function(){})中将文件数据块写入响应,在on('data',function(){})中结束响应处理
第二中方法为nodejs的高级机制,创建数据流后通过pipe()函数将数据流用管道接到WriteStream,且会在其中自动调用res.end()功能。任何ReadStream都能通过pipe()接到WriteStream中。

Events

Node.js有多个内置的事件,我们可以通过引入events模块,并通过实例化EventEmitter类来绑定和监听事件,如下:

var event = require('events');
var eventEmitter = new events.EventEmitter();
var eventHandler = function(args){...};
eventEmitter.on('eventName',eventHandler);
eventEmitter.emit('eventName',args...);

Buffer

Buffer类用于在 TCP 流或文件系统操作等场景中处理字节流。
官方建议构造方法:

  • Buffer.from(buffer)
  • Buffer.from(array)
  • Buffer.from(string[,encoding])
  • Buffer.alloc(size)
  • Buffer.allocUnsafe(size)

Buffer对象的操作方法:

  • write(string[, offset[, length]][, encoding])
  • toString([encoding[, start[, end]]])
    • ascii
    • utf8
    • base64
    • hex
  • toJSON()

Stream

Stream 是一个抽象接口,Node 中有很多对象实现了这个接口。
所有Stream对象都是EventEmitter的实例。常用事件:

  • data
  • end
  • finish
  • error

pipe()方法可将从writeStream流到另一个流中,且可以链式调用,如下:

var fs = require('fs')
fs.createReadStream('input.txt')
    .pipe(fs.createWriteStream('output.txt'))

url && querystring

url模块和querystring模块用来解析请求的url和GET和POST的参数
url用法:

var url = require('url')
url.parse(string)
====================================================
                            url.parse(string).query
                                           |
           url.parse(string).pathname      |
                       |                   |
                       |                   |
                     ------ -------------------
http://localhost:8888/start?foo=bar&hello=world

全局对象

名字 作用
__filename 当前正在执行的脚本的文件名
__dirname 当前执行脚本所在的目录
setTimeout(cb,ms) 在指定的毫秒(ms)数后执行指定函数(cb),只执行一次
clearTimeout(t) 停止一个之前通过 setTimeout() 创建的定时器
setInterval(cb,ms) 指定的毫秒(ms)数后执行指定函数(cb)。返回一个代表定时器的句柄值。不停调用函数
console 控制台标准输出,主要使用log方法

util

util 是一个Node.js 核心模块,提供常用函数的集合。
util.inspect(object): 输出object详细属性。

fs

Node.js提供文件操作API,通过引入fs模块使用。
读取文件:同步readFileSync()|异步readFile()
写入文件:fs.writeFile(file, data[, options], callback)
打开文件:fs.open()

猜你喜欢

转载自www.cnblogs.com/y4ngyy/p/10250885.html