The basic module describes the node

Here Insert Picture Description

1 file system (via node operating system files)

Use the file system to be introduced when fs fs module core module, a direct reference to need to download;

All operations fs module has two forms can be selected synchronous asynchronous

Synchronize file system block the execution, that is, unless the operation is completed, no down side does not execute code,

Asynchronous file does not block the implementation of the program, but the results are returned by the callback function when the operation completes

2buffer (buffer)

and an array of like buffer structure, method of operation and also similar to the array; core module is not necessary to introduce a module

• Buffer from a structural point of view very much like an array, its meta
element hexadecimal digit.
• In practice it means an element of a byte of memory.
• Buffer in memory is not actually using JavaScript
distribution, but at the bottom by a C ++ application.
• that is, we can directly create space in memory by Buffer.

. Are stored in the buffer in binary files but when displayed in hexadecimal display;

Once the buffer size, it can not be modified, in fact, direct operation of the buffer memory of the underlying

var buf=Buffer.alloc(5);//创建一个大小为5字节的buffer
buf[0]=0xaa;//类似于给数组赋值
buf[1]=88;
//注意:索引大于buffer.length-1时,创建的数据将会消失;
console.log(buf);
var buf1=Buffer.from("hello nodejs");//根据内容创建buffer,根据内容创建大小后,不可以修改,将一个字符串转换为buffer
console.log(buf1.length);//返回buf1所占内存的字节数
var buf3=Buffer.allocUnsafe(5);
//创建一个指定大小的buffer,但是可能会有敏感数据,
// 也就是如果别的程序使用过这一块内存,在他创建的时候
// 不会清空,有可能包含数据,而alloc在创建的时候就会先清空;
//性能比alloc好,因为他不清空,而alloc是清空后再创建;
console.log(buf3);
//Buffer.from(str)将一个字符串转换为buffer对象
//Buffer.allocUnsafe(size)创建一个指定大小的buffer 可能会造成数据泄露
//Buffer.alloc(size)创建一个指定大小的buffer,相对安全;

3 File System

• In the Node, the interaction with the file system is very important, the nature of the local server's file will be sent to the remote client
• Node to the file system and fs through interactive module
• This module provides standard file access API to open, read, write files, and interact with it.
• To use the fs module, you first need to load it

All operations are available in synchronous and asynchronous forms • fs module.
• implementation of synchronous file system will block the program, that is, unless the operation is completed, it would not execute the code down.
• asynchronous file system does not block the execution of the program, but when the operation is complete, the results returned by the callback function.

Open
r read a file, the file does not exist, abnormal
r + read and write files, the file does not exist, abnormal
rs file is opened in synchronous mode for reading
rs + file is opened in synchronous mode for reading and writing
w open the file with write operation, if it does not exist to create, if there is truncated
wx open a file for write operations, if there is a failure to open
w + open the file for reading and writing, if it does not exist to create, if there is truncated
wx + open the file for read and write, if there is a failure to open
a file for append open, and if not create
ax open file for append, if the failed path exists
a + additional open files for reading and, if the file does not exist, create
ax + open additional file for reading and, if there is a path fails

Example 4 synchronous write
/*使用同步方法创建文件
第一步打开文件
fs.openSync(路径,打开文件要操作的类型("w"可写/"r"只读),文件操作权限一般不传)
返回值:返回一个文件的描述符作为结果,我们通过描述符对文件进行操作;
第二部写入并保存文件
fs.writeSync(要写入的文件标识符,要写入的字符串内容,[要写入的起始位置,编码格式默认utf-8(这两个参数一般不写)]);
第三部关闭文件*/
fs.closeSync(要关闭文件的标识符);
const fs = require("fs");//引入模块
//打开文件
let fd=fs.openSync("hello.txt","w");
//写入内容
fs.writeSync(fd,"你好世界");
//关闭文件(节约内存)
fs.closeSync(fd);
5 asynchronous file write
// 使用异步方法创建文件
var fs=require("fs");
fs.open("hello2.txt","w",function (error,fd) {
    console.log(arguments);
    //[Arguments] { '0': null, '1': 3 }第一个表示是否成功,如果成功返回null
    // 如果出错,抛出异常
    if(error==null){//表示成功
        console.log("读取成功");
        fs.write(fd,"你好,nodejs",function (err) {
            if(err==null){
                console.log("写入成功");
                fs.close(fd,function (erro) {
                    if(erro==null){
                        console.log("文件已关闭");
                    }else{
                        console.log("文件关闭失败");
                    }
                });
            }else {
                console.log("写入失败");
            }
        })
    }else{
        console.log("读取失败");
    }
})
6 simple file written
//简单文件写入
fs.writeFile(文件路径及文件名(使用双斜杠或一个反斜杠),写入的内容,{改变操作状态可有可无},回调函数);
//引入模块
const fs =require("fs");
fs.writeFile("hello4.txt",'这是一个简单的文件创建',{flag:"w"},function(err){
    console.log(arguments);
    if(err==null){
        console.log("写入成功");
    }else{
        console.log('写入失败');
    }
})

7 streaming file

Synchronous, asynchronous, simple file written not suitable for large file write performance is relatively poor, easily lead to memory overflow;

//流式文件
const fs=require("fs");
var wb=fs.createWriteStream("text.txt");//创建流
wb.once("open",function () {
    //因为开启流只执行一次,所以使用on绑定事件会造成资源浪费
    //所以使用once来绑定一个一次性事件,从而提高性能
    console.log("流打开了");
})
wb.write("这是通过流式操作写入的文件");//将内容写入文件
wb.write("这是通过流式操作写入的文件");//将内容写入文件
wb.write("这是通过流式操作写入的文件");//将内容写入文件
wb.end();//关闭流
wb.once("close",function () {
    console.log("流关闭了");
})

8 synchronization file reading (like a synchronization file write)

9 asynchronous file reading (similar to asynchronous file write)

10 Simple file read

//简单文件读取
const  fs=require("fs");
fs.readFile("text.txt",function (error,data) {
    //第一个参数是要去读取的文件,第二个参数是回调函数
    //error是返回的状态,null为成功,否则抛出异常
    //data是如果成功返回的数据
    console.log(arguments);
    if(error==null){
        console.log(data.toString());
    }
})

11 streaming file read

//流式文件读取
const  fs=require("fs");
var rd=fs.createReadStream("text.txt");//可读流
var wd=fs.createWriteStream("text1.txt");

rd.once("open",function (err) {
    console.log("可读流打开了");
})
rd.once("close",function (err) {
    console.log("可读流关闭了");
})
// rd.on("data",function (data) {
//     console.log(data);
// });
//////////////////////////////////////////////////////////////////
//将读取到的数据给另一个文件
//调用一个方法  pipe 使用可读流读到的数据写入可写流
rd.pipe(wd);

12 other modules

fs.existssync () to check whether there is a path to the file

fs.stat () whether it is a document, returns an object that contains all the information

fs.statsync()

fs.unlink () to delete the file

fs.unlinksync () to delete the file

13 simple http service

//使用node可以轻松创建一个web服务器
//在node中提供了一个核心模块:http
//http就是创建编写服务器的
//1,加载http核心模块
var http=require("http");

//2,创建一个web服务器,使用http.createServer();返回一个server实例
var server=http.createServer();

//3,服务器要干嘛?
    /*对数据提供服务
    发请求
    接收请求
    处理请求
    发送响应
    注册request请求事件
    当客户端发送过来请求request请求事件,然后
    执行第二个参数:回调处理函数
    回调函数(request)有两个形参,
    request请求对象
    请求时,获取客户端的一些数据,如请求路径
    response响应对象
    响应对象可以给客户端发送响应信息
    
    
    注意:响应的数据要么是字符串,要么是buffer
    */
    server.on("request",function(request,response){
        console.log("收到请求了,请求地址"+request.url);
        //response有一个方法write可以给客户端发送响应数据
        //write可以使用多次,但是最后一定要用response.end()来结束响应
        //否则客户端会一直等待
        response.write("hello node");
        response.write("hello javascript");
       // response.write("hello 小天才");write只能写字符串和buffer
          response.end("hello");//上面写入方法基本不用
        response.end();
    });
    //4,绑定端口号启动服务器
    server.listen(3000,function(){
        //打印日志,确认服务器已启动
        console.log("服务器启动了");
    });

14 Port Number

Obtain client port number request.socket.remotePort;

Obtain the IP address of the client

request.socket.remoteAddress;

Example: 300 port is not a port 300 of the server and a client

Note: The range of port numbers is (0-65536), but do not take up some of the default port number, such as port 80 http services;

You can open multiple services at the same time, but the port number can not be the same;

15 in response to data distortion Chinese

In fact, the default server sends the data content is utf-8,

I do not know but the browser is utf-8 encoded content

The browser does not know will be in accordance with the current operating system code to parse the contents of coded case of server response,

Chinese operating system default encoding is gbk

Solution:

Encoding format tells the browser to execute

response.setHeader("Content-Type","text/plain;charset=utf-8");

In the http protocol, Content-Type is to inform the other side of me is what the data encoding, format and content of the response;

text/plain	普通文本
text/html	会解析html标签

content-type table http://tool.oschina.net/

Pictures do not have to set the encoding format, but the file format to write;

jQuery Tips

Using jquery get a collection if you want to use jquery traversal, using foreach in high version

Each used in the low version; acquired set is a pseudo-arrays, but can be converted by the process array; [] slice.call ($ ( "div")).;

express basic usage / basic methods

app.use(express.static('public')) 		//公开静态目录

//公开后就可以访问静态目录中的文件,如下例
//http://localhost:3000/css/style.css

If you are using multiple static resource directory, call repeatedly express.staticmiddleware functions:

However, you provide express.staticthe function of the path is relative to the boot nodedirectory of the process. If you run from another rapid application directory, use the directory you want to provide the absolute path to more secure:

app.use('/static', express.static(path.join(__dirname, 'public')))
Published 80 original articles · won praise 12 · views 3891

Guess you like

Origin blog.csdn.net/weixin_44036436/article/details/101075188