Node. js 4. Basics

Source: Internet
Author: User

 

Encoding:

Node. jsSupportedUTF-8 ("utf8 "),ASCII ("ASCII ")AndBinary ("binary ")Encoding, relatively speaking,ASCIIAndBinaryIt will be faster,UTF-8It will be much slower and should be avoided as much as possible.

 

Globals

Arguments:

VaRSys = require ('sys '),
Some_argument = process. argv [2];

//Argument example

If(! Some_argument ){
ReturnSYS. Puts ('usage: node' + _ filename. Replace (_ dirname + '/', '') + 'some _ argument ');
}

 
//Require example
SYS. Puts ('default require paths: '+ require. paths );

SYS. Puts ('adding current directory to require. Paths ');

Require. paths. unshift (_ dirname );

SYS. Puts ('modfied require. paths: '+ require. paths );
 

 

 

Run

 

Node global. js test_arg

The following information is output:

Adding current directory to require. Paths

Modified require. paths:/home/sinsay/projects/nodejs_example/4. bacics/global. JS,/home/sinsay /. node_modules,/home/sinsay /. node_libraries,/usr/local/lib/node

Sinsay @ Ubuntu :~ /Projects/nodejs_example/4. bacics $ node global. js

 

Process. argvThe command line parameters are saved. In the current example,Argv [0]IsNode, argv [1]IsGlobal. JS,

Argv [2]ParameterSome_argument

If(! Some_argument ){
ReturnSYS. Puts ('usage: node' + _ filename. Replace (_ dirname + '/', '') + 'some _ argument ');
}

 

 

If no parameters are provided during execution, the current script will output the correct method of using the script. And aboveCodeMedium,_ FilenameIs a global variable, which indicates the path of the currently executed file,

And he replaced_ FilenamePath in(_ DirnameIt is also a global variable, indicatingCurrent path)Only the file name is retained.

 

Require

Require. Paths

ProvidedRequireFindPackageOr other things, the path can be usedUnshiftTo add your directory for the search path, like:

Require. paths. unshift (_ dirname );

 

Process

ProcessThe object provides us with information about the current process, such as the processID,Running platform,Memory usage, etc....

You can also provide the exit status code when exiting the script,E. g:

 

Process. Exit (0 );

 

By default, the exit status code is0See the example below.

 

VaR Sys = require ('sys ');

//Dis play all command line arguments
SYS. Puts ('provided arguments :');
For(VaRKeyInProcess. ARGs ){
SYS. Puts (Key + ':' + process. argv [Key]);
}

//Process details (PID, platform, memory usage)
SYS. Puts ('\ npid:' + process. PID );
SYS. Puts ('Platform: '+ process. Platform );
SYS. Puts ('memory usage: '+ process. memoryusage (). RSS );

//Display User Environment
SYS. Puts ('\ nuser environment :');
For(VaRKeyInProcess. env ){
SYS. Puts (Key + ':' + process. env [Key]);
}

//Process exit code-default success code 0
Process. Exit (0 );

 

System Module

SystemThe module provides many ways for us to output information to the console.

 

SYS. Puts () // Output Information and line feed

SYS. Print () // Output information without line feed

SYS. debug ('some debug output ');

// Output Information and add the debug information. e. g:

// Debug: Some debug output

System. Log ('some log output ');
// Output Information, and add the current date and time, e. g:
// 20 Mar 23:17:15-some log output

SYS. Inspect (process. memoryusage ())
// Output information according to the rendering form of the object, e. g:
// {RSS: 5263360
// . Vsize: 41353216
// , Heaptotal: 2176512
// , Heapused: 963872
// }

The following is a sample script.:

VaR Sys = require ('sys ');

//Sys output examples
SYS. Puts ('output with Trailing newline ');
SYS. Print ('output ');
SYS. Print ('new line ');
SYS. Puts ('\ nadd new line to beginning and extra one at the end. \ n ');
SYS. debug ('some debug output ');
SYS. Log ('some log output ');

//Simple SYS. Inspect example
VaRProcess_memory = process. memoryusage ();
SYS. Puts ('\ nprocess. memoryusage ():');
SYS. Puts (SYS. Inspect (process_memory ));

 

 

Timers

 

You canNodeOfProgramUsed inJavascriptOfTimer, suchSetTimeout (), cleartimeout (), setinterval (), clearinterval (). Example:

VaRSys = require ('sys ');

//Simple timeout exapmle
VaRStart_time =NewDate ();
SYS. Puts ('string 2 second timer ');

SetTimeout (Function(){
VaREnd_time =NewDate ();
VaRDifference = end_time.gettime ()-start_time.gettime ();
SYS. Puts ('stopped timer after: '+
Math. Round (difference/1000) + 'seconds ');

Cleartimeout_example ();
},2000 );

function cleartimeout_example () {
var start_time = New date ();
sys. puts ('\ nstarting 30 second timer and stopping it immediately without triggering callback');

var timeout = setTimeout ( function () {
var end_time = New date ();
var difference = end_time.gettime () -start_time.gettime ();
sys. puts ('stoped timer after '+ math. round (difference/1000) + 'seconds');
}, 3000);
cleartimeout (timeout);
interval_example ();
}

FunctionInterval_example (){
VaRStart_time =NewDate ();
SYS. Puts ('\ nstring 2 second interval, stopped after 5th tick ');

VaR Count = 1;
VaR Interval = setinterval ( Function (){
If (COUNT = 5) clearinterval ( This );
VaR End_time = New Date ();
VaR Diffrence = end_time.gettime ()-
Start_time.gettime ();
SYS. Puts ('tick No. '+ Count + 'after' + math. Round (diffrence/1000) + 'second ');
Count ++;
},2000 );
}

 

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.