Cutting edge: Core module 2 is mainly related to the flow, of course, to get a clear understanding of this area, you need to have some understanding of the content in core module 1.

Fs module

For all read methods, the file must exist; for all write methods, if the file does not exist, the file must be created.

  1. fs.readFile() — fs.readFileSync()
let fs=require('fs'); Fs.readfile (fs.readfile)'./1.txt',{encoding:'utf8'},function(err,data) { console.log(err); console.log(data); }); // Synchronous methods have no callback functionslet result=fs.readFileSync('./1.txt',{encoding: 'utf8'});
console.log(result);
Copy the code
  1. fs.writeFile() —fs.weiteFileSync()
const fs=require('fs'); // overwrite the file // fs.writefile ()'./2.txt'.'123',{encoding: 'utf8'},(err) => {
//	console.log('write OK');
//})
fs.writeFileSync('./3.txt'.'456');
Copy the code
  1. fs.appendFile()
const fs=require('fs'); //writeFile flags=w Write, if the file already exists, delete the file before write. //fs.writeFile('./4.txt'.'789',{flag:'a'}); // append to the file without overwriting it'./4.txt'.'789');
Copy the code

The disadvantages of the above three methods are that the whole file is read or written.

  1. fs.open()
fs.open(src, 'r', (err,fd)) // The first argument represents the file, the second means (r, r+, w, w+, a, a+), and the third is the callback, where fd is the file descriptorCopy the code
  1. Fs.read () // Put the contents into memory
letbuffer=Buffer.alloc(6); //[0,1,2,3,4,5] fs.read(fd,buffer,0,3,3,(err,bytesRead) => { // The callback bytesRead indicates the actual bytes console.log(buffer.toString()); });Copy the code
  1. fs.write()
let buffer=Buffer.from('Day day up'); / / / / fd,1,2,3,4,5,6,7,8,9,10,11 [0] buffer offset fs. Write (fd, buffer, 3,6,3, (err, bytesWritten) = > {/ / file descriptors, Buffer,buffer start position,buffer length, file write position, // callback bytesWritten indicates the actual byte console.log(err); fs.fsync(fd,(err) => { fs.close(fd,(err) => { console.log('Close the file');
		});
	});
});
Copy the code
  1. fs.createReadStream()

  2. fs.fsync()

  3. fs.createWriteStream()

Let me give you a little example to help you understand

// pipe
let fs = require('fs');
let rs = fs.createReadStream('./1.txt',{
    highWaterMark:1
})
let ws = fs.createWriteStream('./5.txt',{
    highWaterMark:2
})
let index = 1;
rs.on('data', (data) => {
    console.log(index++)
    letflag = ws.write(data); // The call to writable.write() returns when the total size of the internal writable buffer is less than the threshold set by highWaterMarktrue. Returns once the size of the internal buffer reaches or exceeds highWaterMarkfalse.if(! Flag) {// The internal buffer exceeds highWaterMark rs.pause()}})let wsIndex = 1;
ws.on('drain', () => {
    console.log('ws'+wsIndex++)
    rs.resume()
})
// 1 2 ws1 3 4 ws2 5 6 ws3
Copy the code
  1. fs.stat()
// Read the status of the file; Using fs.stat() to check whether a file exists before calling fs.open(), fs.readfile (), or fs.writefile () is not recommended. // Instead, the user code should open/read/write the file directly and handle errors when the file is invalid. // If you want to check for the existence of a file and not operate on it, fs.access() is recommended.let fs = require('fs');
fs.stat('./1.txt', (err, data) => {console.log(data) // Enumerate several common properties size, ctime, birthtime, mtime})Copy the code
  1. Whether the fs.access() file exists
let fs = require('fs');
fs.access('./1.txt', (err) => {
    console.log(err)
})
Copy the code
  1. fs.mkdir()
// Create a directory. When creating a directory, ensure that the parent directory existslet fs = require('fs');
fs.mkdir('./a/b', (err) => {// an error will be reported if directory A does not exist console.log(err)})Copy the code
  1. fs.rmdir()
// If directory a is not empty, you need to delete the directory in a layer from the inside to the outside. Otherwise, error "directory not empty" is reportedlet fs = require('fs');
fs.rmdir('./a', (err) => {
    console.log(err)
})
Copy the code

TCP modules

// Transport layer HTTP WebSocket is all based on TCP. TCP is a readable and writable stream. // Transport layer HTTP WebSocket (basically the same application)let net = require('net'); / / socketletserver = net.createServer(); // The socket is a readable and writable stream Duplex Server.on (); // The socket is a readable and writable stream.'connection'.function(socket){// socket has no rules. We can emulate HTTP socket.setencoding with TCP ().'utf8');
    socket.on('data'.function(data){ console.log(data); }); Write (' HTTP/1.1 200 OK content-length: 5 hello '); }); server.listen(3000); // We can see hello when we open localhost:3000 in the browserCopy the code

The HTTP module

Var HTTP =require("http");

http.createServer(function(req,res){
    res.writeHead(200,{
        "content-type":"text/plain"
    });
    res.write("hello nodejs"); res.end(); }).listen(3000); // Enter localhost:3000 in the browser and you can see hello nodejsCopy the code

Above is the commonly used nodejs part of the core modules, because involves more not deep inside, each of which can be expanded there are actually a lot of knowledge, in-depth knowledge of the many I myself also is not very understanding, hope some of the above core content can help to you, of course there are many shortcomings of hope friends correct is put forward. I also hope to learn and share with you friends!

Postscript:

The flow covered in this article can be seen in more depth

  • The stream you must ask when interviewing a senior front end engineer

Related content:

  • Nodejs core module (1)