A list,

Node is a server running environment for JavaScript. The term “operating environment” has two meanings: First, the JavaScript language runs on the server through Node, and second, Node provides a number of libraries that allow the JavaScript language to interact with the operating system (such as reading and writing files and creating child processes). In this sense, Node is a JavaScript library. Node.js features are really js features: event-driven, non-blocking I/O.

Buffer object

1. An overview of the

A Buffer is a node interface that processes binary data. It is a global object and does not need to be imported. Is a constructor that generates an array-like object.

var bytes = new Buffer(256);
Copy the code

2. Create the Buffer class

  • Alloc (size[, fill[, encoding]]), returns a Buffer instance of the specified size. If fill is not set, it defaults to 0.
// Create a Buffer of length 10 filled with 0x1. const buf2 = Buffer.alloc(10, 1)Copy the code
  • Buffer.concat(list[, totalLength]), returns a new value of Buffer that is the result of concatenating all Buffer instances together with the list.
  • Buffer.from(array), returns a new Buffer instance initialized by the array’s value (the array elements passed in must be numbers, otherwise zeros will automatically be overwritten)
  • Buffer.from(string[, encoding]), converts string to Buffer.
  • Buf. write(string[, offset[, length]][, encoding]), writes to the buffer, returns the actual write size.
buf = Buffer.alloc(256);
len = buf.write("www.runoob.com");
Copy the code
  • Buf.tostring ([encoding[, start[, end]]]), reads Node buffer data. Return value: Decodes buffer data and returns a string using the specified encoding.
const buf = Buffer.alloc(10,'123');
buf.write('jucious') console.log(buf.tostring ()) // New characters will overwrite the previous onesCopy the code
  • Buffer.concat(list[, totalLength])
var buffer1 = Buffer.from(('Rookie Tutorial'));
var buffer2 = Buffer.from(('www.runoob.com'));
var buffer3 = Buffer.concat([buffer1,buffer2]);
Copy the code

Third, EventEmitter

Many objects in Node.js emit events: a net.Server object fires an event every time a new connection is created, and a fs.readStream object fires an event every time a file is opened. All of these event-producing objects are instances of events.EventEmitter.

  • The EventEmitter class Events module provides only one object: Events.eventEmitter. The core of EventEmitter is the encapsulation of event triggering and event listener functions.
    var EventEmitter = require('events').EventEmitter; 
    var event = new EventEmitter(); 
    event.on('some_event'.function() { 
        console.log('some_event event triggered '); 
    }); 
    setTimeout(function() { 
        event.emit('some_event'); 
    }, 1000); 
Copy the code

The Stream is on the Stream.

  • Overview “Stream” is a way of dealing with the system cache. The operating system reads data in chunks and stores the data in the cache every time it receives it. Node applications can handle the cache in two ways. The first is to wait until all data is received and then read from the cache at once, which is the traditional way of reading files. The second is to use a “data stream” approach, in which a piece of data is read as it is received, that is, the data is processed before it is received. The biggest feature of the data flow interface is that it communicates through events. With readable, Writable, drain, data, End, and close events, it can read and write data. When reading or writing data, a data event will be triggered every time a piece of data is read (or written). When all the data is read (or written), the End event will be triggered. An error event is raised if an error occurs. Data can be read from or written to an object as long as the data flow interface is deployed. The Stream interface is deployed in Node for many objects involved in IO processing, such as file read and write, HTTP request read and write, TCP connection, and standard INPUT and output.
  • The fs.createreadStream method reads a file as a “data stream.” This can be output to standard output while the file is still being read. This is obviously very beneficial for reading large files.
var fs = require("fs");
var data = ' '; Var readerStream = fs.createreadStream ('input.txt'); // Set the encoding to UTf8. readerStream.setEncoding('UTF8'); --> data, end, and error readerstream.on ()'data'.function(chunk) {
   data += chunk;
});
readerStream.on('end'.function(){
   console.log(data);
});
Copy the code
  • stream
var writerStream = fs.createWriteStream('output.txt'); // Use utf8 encoding to write data writerstream.write ('hello'.'UTF8'); // Indicates that data is no longer written to Writable. writerStream.end(); --> data, end, and error writerStream.on()'finish'.function() {
    console.log("Write complete.");
});
Copy the code
  • The pipe flow

    Pipes provide an output-to-input flow mechanism and are typically used to fetch data from one stream and pass it to another.


    As shown in the picture above, we compare the file to a bucket containing water, and the water is the content of the file. We connect two buckets with a pipe to make the water flow from one bucket to the other, which is gradually realizedThe process of copying large files.

    Syntax: readable.pipe(Destination [, options]) This readable.pipe() method attaches a Writable stream to readable.

Var readerStream = fs.createreadStream ('input.txt'); Var writerStream = fs.createWritestream ('output.txt'); TXT file and write the content to output. TXT readerstream. pipe(writerStream);Copy the code
  • Chain flow
var fs = require("fs");
var zlib = require('zlib'); // Compress the input.txt file into input.txt.gz fs.createreadstream ('input.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('input.txt.gz'));
Copy the code

5. Global objects

The global object in Node.js is global, and all global variables (except global itself) are properties of the global object.

  • __filename __filename specifies the name of the script that is being executed. It prints the absolute path to the file location, and may not be the same as the file name specified by the command line argument. If in a module, the value returned is the path to the module file.
  • __dirName __dirname indicates the directory where the script is currently executed.
  • Process An object that describes the state of the current Node.js process and provides a simple interface to the operating system. You’ll usually have to deal with it when you’re writing a native command line program.

6. Fs module

  • ReadFile (), readFileSync ()
var fs = require("fs"Fs.readfile ()'input.txt'.function (err, data) {
   if (err) {
       return console.error(err);
   }
   console.log("Asynchronous read:"+ data.toString()); }); Var data = fs.readfilesync ('input.txt');
Copy the code
  • The writeFile (), writeFileSync ()
// Async can encode fs.writefile ('message.txt'.'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('It\'s saved!'); }); // synchronize fs.writeFileSync(fileName, STR, 'utf8');
Copy the code
  • Mkdir () The mkdir method is used to create a directory. Mkdir takes three arguments, the first a directory name, the second a permission value, and the third a callback function.
var fs = require('fs');
fs.mkdir('./helloDir', 0777,function (err) {
  if (err) throw err;
});

Copy the code
  • The readdir() eaddir method is used to read a directory, returning an array of contained files and subdirectories.
  • Open file The following syntax is used to open files in asynchronous mode: fs.open(path, flags[, mode], callback), flags-file opening behavior.
var fs = require("fs"); // Asynchronously open the file console.log("Ready to open the file!");
fs.open('input.txt'.'r+'.function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("File opened successfully!");     
});
Copy the code
  • Stat () fs.stat(path, callback),callback – callback function with two arguments such as :(err, stats), stats is the fs.stats object.
var fs = require('fs');
fs.stat('/Users/liuht/code/itbilu/demo/fs.js'.function (err, stats) {
    console.log(stats.isFile());         //true
})
Copy the code
  • Watchfile (), unwatchFile () The watchfile method listens for a file and automatically triggers a callback function if the file changes.
var fs = require('fs');
fs.watchFile('./testFile.txt'.function (curr, prev) {
  console.log('the current mtime is: ' + curr.mtime);
  console.log('the previous mtime was: ' + prev.mtime);
});
fs.writeFile('./testFile.txt'."changed".function (err) {
  if (err) throw err;
  console.log("file write complete");   
});
Copy the code

The unwatchfile method is used to unlisten a file.

  • CreateReadStream () The createReadStream method is often used to open large text files and create a data stream for reading operations. The so-called large text file refers to the text file is too large for the cache of read operations, and can only be divided into several times to send. Each sending will trigger a data event, and the end event will trigger the end event. (See 4, Stream)
  • CreateWriteStream () The createWriteStream method creates a write data stream object with a write method for writing data and an end method for terminating the write. The createWriteStream method works with the createReadStream method to copy large files.
function fileCopy(filename1, filename2, done) {
  var input = fs.createReadStream(filename1);
  var output = fs.createWriteStream(filename2);
  input.on('data'.function(d) { output.write(d); });
  input.on('error'.function(err) { throw err; });
  input.on('end'.function() {
    output.end();
    if (done) done(a); }); }Copy the code

7. Web module

1. Basic usage

1.1 Processing GET Requests

var http = require('http');
var fs = require('fs'); // Call the createServer method of the HTTP module to create a server instance http.createserver (function(request, response){ <! Fs.readfile (fs.readfile)'data.txt'.function readData(err, data) {
    response.writeHead(200, {'Content-Type': 'text/plain'}); response.end(data); }); <! -- Fs.createreadStream ('${__dirname}/index.html`).pipe(response);
}).listen(8080, '127.0.0.1');
Copy the code

The response.end method is used to write the HTTP response and close the conversation when the response is complete.

1.2 the request object

The first argument to the createServer method’s callback is a Request object with the following attributes: URL: the url from which the request was made; Method: indicates the HTTP request method. Headers: all HTTP headers of an HTTP request.

  • Gets the pathname of the request
var url = require('url');
var pathname = url.parse(request.url).pathname;
Copy the code
  • The setEncoding() method is used to set the encoding of the request.
request.setEncoding("utf8");
Copy the code

1.3 Processing POST Requests

Var HTTP = require('http');
http.createServer(function (req, res) {
  var content = "";
  req.on('data'.function (chunk) {
    content += chunk;
  });
  req.on('end'.function () {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("You've sent: " + content);
    res.end();
  });

}).listen(8080);
Copy the code

The data event is emitted every time a piece of data is received, and the received data is passed into the callback function. The end event is emitted after all data has been received. Modify the above code slightly, you can make the file upload function.

http.createServer(function (request, response) {
  response.writeHead(200);
  file = fs.createWriteStream("destination.md");
  request.pipe(file);
  fileSize = request.headers['content-length'];
  uploadedBytes = 0;
  request.on('data'.function (d) {
    uploadedBytes += d.length;
    var p = (uploadedBytes / fileSize) * 100;
    response.write("Uploading " + parseInt(p, 0) + " %\n");
  });
  request.on('end'.function () {
    response.end("File Upload Complete");
  });
}).listen(3030, function () {
  console.log("server started");
});
Copy the code

2. Make a request

2.1 the get ()

function getMsg(callback) {
  return http.get({
    host: 'personatestuser.org',
    path: '/email'
  }, function(response) {
    var data = ' ';
    response.on('data'.function(d) {
      data += d;
    });
    response.on('end'.function() {
      var parsed = JSON.parse(data);
      callback({
        email: parsed.email,
        password: parsed.pass
      });
    });
  });
},
Copy the code

2.2 the post ()

The equest method is used to issue an HTTP request in the format http.request(options[, callback]). Here is an example of sending a POST request.

const postData = querystring.stringify({
  'msg': Hello world
});
const options = {
  hostname: 'nodejs.cn',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'.'Content-Length': Buffer.byteLength(postData) } }; Const req = http.request(options, (res) => {console.log(' status code:${res.statusCode}`); Console. log(' response header:${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {console.log(' body of the response:${chunk}`);
  });
  res.on('end', () => {
    console.log('No data in response');
  });
});
req.on('error', (e) => {console.error(' Request encountered a problem:${e.message}`); }); // Write data to the request body. req.write(postData); req.end();Copy the code