The console module

The console module in Node.js provides a console debug output mechanism similar to the console object in Chrome.

This module exports two members: (1) Console class: can be used to execute output to any Node.js output stream object; (2) Global. console instance: can be used to execute output to stdout and stderr.

The console object

The creation of the global.console object

global.console=new Console(process.stdout,process.seterr);
Copy the code

Process. stdout: standard output stream object of the current process process.stderr: Standard error stream object of the current process

You can also create your own console object:

const cs =require('console');
const fs=require("fs");
const out =fs.createWriteStream('./appout.log');
const err=fs.createWriteStream('./apperr.log');

const logger=new cs.Console(out,err);
var count=5;
logger.log('count:%d',count);
logger.error('count:%d',count);
Copy the code

OS module

The OS module provides many methods for obtaining information about the current operating system.

const os=require('os');

os.EOL									// A constant representing OS end-of-line
os.tmpdir()							// Return to the temporary directory of OS
os.hostname()						// Returns the current host name
os.plateform()					// Returns the current OS platform type
os.uptime()							// Return the current and run times (/ second)
os.loadavg()						// Returns the system load averages of 1 minute, 5 minutes, and 15 minutes
os.totalmem()						// Returns the total OS memory size in bytes
os.freemem()						// Returns the current size of OS free memory, in bytes
os.cpus()								// Returns information about all CPU cores
os.networkInterfaces()	// Returns information about all network interfaces
Copy the code

Readline module

The Interface object provided by the readline module can be used to read data line by line from standard input objects or other input stream objects.

const readline=require('readline');
var reader=readline.createInterface({
	input:process.stdin,
  output:process.stdout
});
reader.question('Please enter user name :',(line)=>{
	console.log('The username you entered is: %s... ',line);
  reader.close();// The interpreter will not exit unless it is closed
})
Copy the code

Interface objects

The Interface object provides the following members for use:

Property member: INPUT: specifies the source from which to read data. Output: specifies the target link to write data to

Method members: wirte () : writes data to the specified output object close () : closes the input stream setPrompt () : sets the input prompt prompt () : outputs the prompt information

Event members: line: reads a row of data. End: reads the end of the input stream. Close: closes the input stream

Use the readline module to simulate the effect of a MySQL command interpreter:

const readline=require('readline');
const reader=readline.createInterface(process.stdin,process.stdout);
reader.setPrompt('MySQL>');
reader.prompt();
reader.on('line',(line)=>{
	if(line==='quit'){
  	reader.close();
    return;
  }
  console.log('Executing... %s',line);
  reader.prompt();
}).on('close', () = > {console.log('Bye! ');
  process.exit(0);
})
Copy the code

Use the readline module to read and print the contents of the file line by line:

const fs=require("fs");
const readline=require('readline');

var file=fs.createReadStream('./log/out.log');
var reader=readline.createInterface(file,process.stdout);
var num=0;
reader.on('line',(data)=>{
    num++;
    console.log(num+":"+data);
})
reader.on('end', () = > {console.log('reading end');
})
reader.on('close', () = > {console.log('closeing... ');
    process.exit(0);
})
/ / 1:12 1212
"/ / 2222
3232 / / devious
/ / came in 4242
/ / 5:52 5252
//closeing...
Copy the code

The Query String module

The Query String module provides operations on the Query String part of the URL.

const queryString=require('querystring');

var qs='ie=utf-8&f=8&rsv_bp=1&srcqid=3605558453180587995'
// Parse the data object from the query string
console.log(querystring.parse(qs));

var data={cid:'sports'.size:'10'.pon:'2'};
// Convert the data object to a query string
console.log(querystring.stringify(data));
console.log(querystring.stringify(data,"#"));// You can specify a separator for each key/value pair. The default is ampersand
console.log(querystring.stringify(data,"#".":"));// The separator between key and value can also be specified as = by default
/ / {
// ie: 'utf-8',
// f: '8',
// rsv_bp: '1',
// srcqid: '3605558453180587995'
/ /}
//cid=%E4%BD%93%E8%82%B2&size=10&pon=2
//cid=%E4%BD%93%E8%82%B2#size=10#pon=2
//cid:%E4%BD%93%E8%82%B2#size:10#pon:2
Copy the code

The querystring module can only parse part of the querystring, so sometimes you need to use the URL module if you want to parse the full URL.

URL module

The URL module provides operations related to handling different parts of the URL. Contains the following three methods:

const url=require('url');

var requsetUrl='https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&srcqid=3605558453180587995&tn=48020221_20_hao_pg&wd= online flow chart & Oq = Vision %25E8% 25BD%25AF%25E4%25BB%25B6%25E4%25B8%258B%25E8%25BD%25BD&rsv_pq=92df9c4000008d95&rsv_t=1b60taNY6%2BTiridgfP1UaAHne4AOFCHaJ asM1Pf8w7rWdCrjxsUDU1aJYYYtiTW6fb%2FpDC%2F%2F%2FM6V&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=35&rsv_sug1=33&rsv_sug7=100 &bs= Vision software Download '
console.log(url.parse(requsetUrl));// Parse out the components of YRL
console.log(url.parse(requsetUrl,true));// Parse the query string into an object

var urlObj={
  protocol:"http:".slashes:true.auth:"tom:123".port:"8080".hostname:"www.baidu.com".hash:"#section3".query: {pno:"2"},
  pathname:"/news/n1"
};
console.log(url.format(urlObj));

var baseUrl='/project/static/base.html';
console.log(url.resolve(baseUrl,'.. /img/1.jpg'));// Resolve relative urls to base addresses
Copy the code

The Path module

The Path module provides methods for manipulating file paths. These methods simply perform string correlation conversions and have nothing to do with the file system itself.

const path=require('path');

// Parse the path string
console.log(path.parse('c:/user/local/img/1.jps'));
// Convert the path object to a string
var obj={dir:'c:/user/local/img'.base:'1.jps'};
console.log(path.format(obj));
// Resolve the absolute path of a destination path with more basic paths
console.log(path.resolve('htdocs/css'.'.. /img/news'));
// More basic path, get template path expected relative relationship
console.log(path.relative('htdocs/css'.'htdocs/img/news'));
/ / {
// root: 'c:/',
// dir: 'c:/user/local/img',
// base: '1.jps',
// ext: '.jps',
// name: '1'
/ /}
//c:/user/local/img\1.jps
//H:\myNode\lesson01\htdocs\img\news
/ /.. \img\news
Copy the code

DNS module

The DNS module provides bidirectional domain name to IP address resolution. There are three main methods:

const dns=require('dns');
dns.lookup('baidu.com',(err,address,family)=>{
    if (err) throw err;
    console.log("The IP address queried by lookup is :",address);// Resolve a domain name to an IP address
    console.log("Lookup IP address format :IPv",family)
})
dns.resolve('baidu.com',(err,addresses)=>{
    if (err) throw err;
    console.log(addresses);// Resolve a domain name into an array of DNS records
})
dns.reverse('60.221.254.230',(err,hostnames)=>{
    if (err) throw err;
    console.log(hostnames);// Reverse resolve an IP address into a set of domain names
})
//lookup The IP address is 39.156.69.79
The IP address format is IPv 4
/ / / '220.181.38.148', '39.156.69.79'
/ / / '230.254.221.60. Adsl - pool. Sx. Cn']
Copy the code

Lookup can be implemented without networking, depending on the underlying operating system, and whether the family parameter returns ipv4 or ipv6. Resolve does not depend on underlying operating systems and requires computers to be connected to the Internet. Use the DNS server to search for all IP addresses corresponding to the domain name, including multiple IP addresses. If no IP address is queried, err is returned.

Util module

The Util module provides several utility methods that other Node.js modules and application developers can use.


// Use a format string with a placeholder
var data={name:"Cola".price:2.5.isOnsale:false};
console.log(
    util.format('Name:%s,PRICE:%d,ISONSALE:%s,JSON:%j',
                data.name,data.price,data.isOnsale,data)
)
// Returns a string representation of an object
console.log(util.inspect(data));
Copy the code

Inheritance between constructors can also be implemented using the Util module

const util=require("util");
const EventRmitter=require('events');

function DBConnection(){
	EventEmitter.call(this);
}
util.inherits(DBConnection,EventEmitter);

var conn=new DBConntion();
console.log(conn instanceof DBConnection);			//true
console.log(conn instanceof EventEmitter);			//true
console.log(DBConnection.super_===EventEmiter);	//true
Copy the code

The Error module

Node.js “error objects” are divided into four types: (1) Error types provided by native JS, such as EvalError, SyntaxError, RangeError, ReferenceError, TypeError, URIError; (2) automatic errors caused by the underlying restrictions of the operating system, such as opening non-existent files, writing data to the closed stream; (3) assertion error; (3) User-defined errors thrown by the application.

All Error objects in Node.js are instances of Error, and Error objects can be thrown using the throw keyword.

Error handling

Errors thrown in synchronous function calls are implemented directly using the throw keyword. Try… Catch results to be captured for further processing; If not, the program crashes.

const fs=require("fs");
// Synchronize function calls
try{
	var data=fs.readFileSync('Nonexistent file.txt');
}catch(err){
	console.log(err);
}
Copy the code

Error objects thrown in asynchronous function calls cannot use try… Catch structure to catch! The error object is typically passed as the first argument to the asynchronous callback function.

const fs=require('fs');
// Asynchronous function calls
fs.readFile('Nonexistent file.txt',(err,data)=>{
	if(err){
  	console.log('File read failed');
    return;
  }
  console.log('File contents:',data.toString())
})
Copy the code

When an asynchronous function call occurs on an EventEmitter object, the resulting error object can be processed by listening for its error time.

const net=require("net");

var connection=net.connection('192.168.0.100');

connection.on('error',(err)=>{
	console.log('Unable to connect to target host');
  return;
});
Copy the code