[NodeJS] Simple explanation of common modules

Source: Internet
Author: User
Tags stdin

First, global objects

Common Global Object __dirname, __filename

__dirname the directory name of the current module, equivalent to Path.dirname (__filename)

__filename the file name of the current module, which is the absolute path.

Second, module explanation 1, OS module
var os = require ("OS"); Console.log ("platform:", Os.platform ()); Console.log ("Release:"  , Os.release ()); Console.log ("type:", Os.type ()); Console.log ("arch:", Os.arch ());

2. Process Module

The process object is a global universal object that controls the current Nodejs process. Because it is always available to node, you can dispense with require ()

// process is a global variable // the path of the current process Console.log (PROCESS.CWD ()); Console.log (Process.chdir ("./filepath"));p Rocess.stdout.write (" Hello World ");p rocess.stderr.write (" error "); // Process.on () Listener Events function (code) {    Console.log (code);}); Process.on (function(err) {    console.log (err);}); Process.exit ();

Standard input/output stream

Process.stdin Readable stream

Process.stdout writable Stream

Process.stderr

process.stdin.resume ();p rocess.stdin.setEncoding("Utf-8");p rocess.stdin.on (function (text) {    process.stdout.write (text.touppercase ());});

Obtaining platform information through the Process object

Process.arch returns a string that identifies the processor architecture ' arm ', ' ia32 ', ' x64 '

Process.memoryusage () Returns an object that describes the memory usage in the current process with 4 properties: RSS, Heaptotal, heapused, external

Process.exit () Through the Code status code to determine whether the program is normal exit or error exit, when the program is finished, you can pass echo $ in the terminal? or echo%errorlevel% to get the status code.

Process.pid property, returns the ID number of the process

The process object implements the Eventemitter event interface, so you can add listeners to it.

The Process.nexttick () method allows you to place the callback method on the first of the next event polling queue. That means you can delay this callback method slightly, which is more efficient than settimeout () setting a delay of 0 milliseconds.

3. Console Object

Format placeholders

%s%d%j

String Numeric JSON

When you print an object, if you do not use%J, the system calls the Util.inspect method to format the object by default.

In fact Console.log Console.error Console.info Console.warn These four methods internally are used by the process to provide stdin, stdout, stderr these three objects to achieve.

You can redirect error messages in a program's run through 2> [FileName] in the console instead of printing in the console. This is because within the operating system there is a total of three standard stream stdin, stdout, stderr. Corresponding numbers 0, 1, 2 respectively

var name = ' Joyjoe '; var user = {name: ' Joyjoe '};console.log (' Hello: ' , name); Console.log (' Hello:%s ' , name) ; Console.log (' Hello:%j ' , user); Console.err (' Error, Bad User: ', user);
2>error.log

Console.trace ()

Console.time () and Console.timeend () Two methods for time benchmark testing

4. URL Module
varurl = require ("url");varBaseURL = 'http://nodejs.cn/api/stream.html#stream_readable_setencoding_encoding "; Url.parse (BaseURL); var queryurl =" https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=node%20url&rsv_pq= C64714e100067de8&rsv_t=90619gdywxr98m%2bjt1vffgij5qlvjwclw215zhvvtnesrje%2fic4nboa4h%2fo&rqlang=cn &rsv_enter=1&rsv_sug3=14&rsv_sug1=11&rsv_sug7=100 "; Url.parse (Queryurl); Url.parse (QueryURL, True ); var json = {protocol:' https: ', Slashes:true, Auth:null, Host:' Www.baidu.com ', Port:null, hostname:' Www.baidu.com ', Hash:null, search:'? Ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu ', query:' Ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu ', Pathname:'/a/b/s ', Path: '/a/b/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu ', href:' Https://www.baidu.com/a/b/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu '};url.format (JSON);

5. Path module

Path.join () uses a platform-specific delimiter to stitch together all the given path fragments and normalize the resulting path

Path.dirname () returns a directory name for a path path

Path.basename () returns the last part of a path

Path.extname () returns the extension of a path path (starting with the last. Number)

6. Timer module

The timer module exposes the global API, which is used to invoke the dispatch function at a certain time period.

The timeout class, created internally, is returned from settimeout () and SetInterval (). Can be passed to cleartimeout () and Clearinterval () to cancel the scheduled operation

When you book a timeout timer class, the Nodejs event loop mechanism continues to run as long as the timer is active. The default behavior of the timer can also be controlled through the ref () and unref () functions.

When Timeout.ref () is called, the event loop is required to not exit as long as the timer is active. By default, all timers are active.

Timeout.unref () when called, the active timer requires exiting the event loop. This means that when all the timers are running (there is no timer class active in the program), the process exits.

Setimmediate (callback, ... args) scheduled to execute immediately callback these callback functions execute immediately after the callback function of the IO event is executed. This means that the immediate function is called before the interval function.

This method is called multiple times, and multiple callback functions are executed sequentially in the order in which they were created. The entire callback queue is processed each time the event loop iterates. If an immediate execution timer is created and is queued by the currently executing callback, the timer will not be triggered until the next iteration of the event loop. The Process.nexttick () method specifies the callback function, which, in front of the callback method, is placed first on the next event polling queue. It can also be understood to be executed after the current event polling has ended.

[NodeJS] Simple explanation of common modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.