Skip to content

Instantly share code, notes, and snippets.

@ngot
Last active May 20, 2017 16:02
Show Gist options
  • Save ngot/c015aca16518f1d77ef5e26b010c2866 to your computer and use it in GitHub Desktop.
Save ngot/c015aca16518f1d77ef5e26b010c2866 to your computer and use it in GitHub Desktop.

Summary

Members Descriptions
namespace assert Assertion test module, if testing result is false, you will get an error. The way of handling error can be set as continue or throw exception.
namespace base32 base32 module with encode and decode operations. to use:
namespace base64 base64 module with encode and decode operations. to use:
namespace base64vlq base64vlq module with encode and decode operations. to use:
namespace bson bson module with encode and decode operations. to use:
namespace console console module
namespace coroutine Concurrency control module.
namespace crypto Encryption algorithm module.
namespace db Database access module.
namespace encoding module with encode and decode operations between hex and other format data. to use:
namespace fs file system module
namespace gd Image processing module.
namespace global Global object, which can be accessed by all scripts.
namespace hash Message digest calculation module, can be used to calculate the message digest and summary Signature.
namespace hex module with encode and decode operations between hex and string. to use:
namespace http HTTP transfer protocol module, handels http protocol.
namespace iconv iconv Module with encode and decode operations between text and binary. to use:
namespace io IO module.
namespace json json module with encode and decode operations. to use:
namespace mq Message queue module.
namespace net Network module.
namespace os Operating system and file system module.
namespace path File path module.
namespace process Process handle module, to manage current process resources.
namespace profiler Memory profiler module.
namespace re Regexp module.
namespace rpc RPC module.
namespace ssl ssl/tls module
namespace test Test Suite module that defines the test suite management.
namespace util Common tools module.
namespace uuid uuid unique id module
namespace vm Safe SandBox module, to isolate runtime based on safety level.
namespace websocket websocket support module
namespace xml xml module
namespace zip Zip file processing module.
namespace zlib zlib compression and decompression module
class AsyncWait MessageHandler object for asynchronous waiting.
class Buffer Binary buffer used in dealing with I/O reading and writing.

namespace assert

Assertion test module, if testing result is false, you will get an error. The way of handling error can be set as continue or throw exception.

how to use:

var assert = require('assert');

or using testing unit:

var test = require('test');
var assert = test.assert;

or you can use test.setup to set up test:

require("test").setup();

Summary

Members Descriptions
public static static ok(Value actual,String msg) Return true when the testing result is ture, assertion failed when return false.
public static static notOk(Value actual,String msg) Return true when the testing result is false, assertion failed when return true.
public static static equal(Value actual,Value expected,String msg) Test value should match the expected one, assertion failed when not match.
public static static notEqual(Value actual,Value expected,String msg) Test value should not have to match the expected one, assertion failed when match.
public static static strictEqual(Value actual,Value expected,String msg) Test value should strictly match the expected one, assertion failed when not match.
public static static notStrictEqual(Value actual,Value expected,String msg) Test value should not have to strictly match the expected one, assertion failed when match.
public static static deepEqual(Value actual,Value expected,String msg) Test value should deeply match the expected one, assertion failed when not match.
public static static notDeepEqual(Value actual,Value expected,String msg) Test value should not have to deeply match the expected one, assertion failed when match.
public static static closeTo(Value actual,Value expected,Value delta,String msg) Test value should closely match the expected one, assertion failed when not match.
public static static notCloseTo(Value actual,Value expected,Value delta,String msg) Test value should not have to closely match the expected one, assertion failed when match.
public static static lessThan(Value actual,Value expected,String msg) Test value should less than the expected one, assertion failed when get a greater or equal one.
public static static notLessThan(Value actual,Value expected,String msg) Test value should not have to less than the expected one, assertion failed when get a less one.
public static static greaterThan(Value actual,Value expected,String msg) Test value should greater than the expected one, assertion failed when get a less or equal one.
public static static notGreaterThan(Value actual,Value expected,String msg) Test value should not have to greater than the expected one, assertion failed when get a greater one.
public static static exist(Value actual,String msg) Test value should be an existed one, assertion failed when the value is not existed.
public static static notExist(Value actual,String msg) Test value should not be an existed one, assertion failed when the value is existed.
public static static isTrue(Value actual,String msg) Test value should be the Boolean true, assertion failed when the value is false.
public static static isNotTrue(Value actual,String msg) Test value should be the Boolean false, assertion failed when the value is true.
public static static isFalse(Value actual,String msg) Test value should be the Boolean false, assertion failed when the value is true.
public static static isNotFalse(Value actual,String msg) Test value should be the Boolean true, assertion failed when the value is false.
public static static isNull(Value actual,String msg) Test value should be the null, assertion failed when the value is not null.
public static static isNotNull(Value actual,String msg) Test value should not be the null, assertion failed when the value is null.
public static static isUndefined(Value actual,String msg) Test value should be the undefined, assertion failed when the value is not undefined.
public static static isDefined(Value actual,String msg) Test value should not be the undefined, assertion failed when the value is undefined.
public static static isFunction(Value actual,String msg) The type of test value should be Function, assertion failed when the value is not a function.
public static static isNotFunction(Value actual,String msg) The type of test value should not be Function, assertion failed when the value is a function.
public static static isObject(Value actual,String msg) The type of test value should be Object, assertion failed when the value is not a object.
public static static isNotObject(Value actual,String msg) The type of test value should not be Object, assertion failed when the value is a object.
public static static isArray(Value actual,String msg) The type of test value should be Array, assertion failed when the value is not an array.
public static static isNotArray(Value actual,String msg) The type of test value should not be Array, assertion failed when the value is an array.
public static static isString(Value actual,String msg) The type of test value should be String, assertion failed when the value is not a string.
public static static isNotString(Value actual,String msg) The type of test value should not be String, assertion failed when the value is a string.
public static static isNumber(Value actual,String msg) The type of test value should be Number, assertion failed when the value is not a number.
public static static isNotNumber(Value actual,String msg) The type of test value should not be Number, assertion failed when the value is a number.
public static static isBoolean(Value actual,String msg) The type of test value should be Boolean, assertion failed when the value is not a boolean.
public static static isNotBoolean(Value actual,String msg) The type of test value should not be Boolean, assertion failed when the value is a boolean.
public static static typeOf(Value actual,String type,String msg) The type of test value should be the specified one, assertion failed when the value type is not match.
public static static notTypeOf(Value actual,String type,String msg) The type of test value should not be the specified one, assertion failed when the value type is match.
public static static property(Value object,Value prop,String msg) The test value should contain the specified property, assertion failed when the property not be contained.
public static static notProperty(Value object,Value prop,String msg) The test value should not contain the specified property, assertion failed when the property contained.
public static static deepProperty(Value object,Value prop,String msg) The test value should deeply contain the specified property, assertion failed when the property not be contained.
public static static notDeepProperty(Value object,Value prop,String msg) The test value should not deeply contain the specified property, assertion failed when the property contained.
public static static propertyVal(Value object,Value prop,Value value,String msg) The specified property of test value should equal the given one, assertion failed when not match.
public static static propertyNotVal(Value object,Value prop,Value value,String msg) The specified property of test value should not equal the given one, assertion failed when match.
public static static deepPropertyVal(Value object,Value prop,Value value,String msg) The specified property of test value should deeply equal the given one, assertion failed when not match.
public static static deepPropertyNotVal(Value object,Value prop,Value value,String msg) The specified property of test value should not deeply equal the given one, assertion failed when match.
public static static throws(Function block,String msg) The block code should throw an error, assertion failed when not throw one.
public static static doesNotThrow(Function block,String msg) The block code should not throw an error, assertion failed when throw one.

Members

public static static ok(Value actual,String msg)

Return true when the testing result is ture, assertion failed when return false.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static notOk(Value actual,String msg)

Return true when the testing result is false, assertion failed when return true.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static equal(Value actual,Value expected,String msg)

Test value should match the expected one, assertion failed when not match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static notEqual(Value actual,Value expected,String msg)

Test value should not have to match the expected one, assertion failed when match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • expected expected value from unittest

  • msg The message of assertion failed when return false.

public static static strictEqual(Value actual,Value expected,String msg)

Test value should strictly match the expected one, assertion failed when not match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static notStrictEqual(Value actual,Value expected,String msg)

Test value should not have to strictly match the expected one, assertion failed when match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static deepEqual(Value actual,Value expected,String msg)

Test value should deeply match the expected one, assertion failed when not match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static notDeepEqual(Value actual,Value expected,String msg)

Test value should not have to deeply match the expected one, assertion failed when match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static closeTo(Value actual,Value expected,Value delta,String msg)

Test value should closely match the expected one, assertion failed when not match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • delta Approximate decimal precision.

  • msg The message of assertion failed when return false.

public static static notCloseTo(Value actual,Value expected,Value delta,String msg)

Test value should not have to closely match the expected one, assertion failed when match.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • delta Approximate decimal precision.

  • msg The message of assertion failed when return false.

public static static lessThan(Value actual,Value expected,String msg)

Test value should less than the expected one, assertion failed when get a greater or equal one.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static notLessThan(Value actual,Value expected,String msg)

Test value should not have to less than the expected one, assertion failed when get a less one.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static greaterThan(Value actual,Value expected,String msg)

Test value should greater than the expected one, assertion failed when get a less or equal one.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static notGreaterThan(Value actual,Value expected,String msg)

Test value should not have to greater than the expected one, assertion failed when get a greater one.

Parameters

  • actual The value need to be tested.

  • expected The expected value.

  • msg The message of assertion failed when return false.

public static static exist(Value actual,String msg)

Test value should be an existed one, assertion failed when the value is not existed.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static notExist(Value actual,String msg)

Test value should not be an existed one, assertion failed when the value is existed.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isTrue(Value actual,String msg)

Test value should be the Boolean true, assertion failed when the value is false.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotTrue(Value actual,String msg)

Test value should be the Boolean false, assertion failed when the value is true.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isFalse(Value actual,String msg)

Test value should be the Boolean false, assertion failed when the value is true.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotFalse(Value actual,String msg)

Test value should be the Boolean true, assertion failed when the value is false.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNull(Value actual,String msg)

Test value should be the null, assertion failed when the value is not null.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotNull(Value actual,String msg)

Test value should not be the null, assertion failed when the value is null.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isUndefined(Value actual,String msg)

Test value should be the undefined, assertion failed when the value is not undefined.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isDefined(Value actual,String msg)

Test value should not be the undefined, assertion failed when the value is undefined.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isFunction(Value actual,String msg)

The type of test value should be Function, assertion failed when the value is not a function.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotFunction(Value actual,String msg)

The type of test value should not be Function, assertion failed when the value is a function.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isObject(Value actual,String msg)

The type of test value should be Object, assertion failed when the value is not a object.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotObject(Value actual,String msg)

The type of test value should not be Object, assertion failed when the value is a object.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isArray(Value actual,String msg)

The type of test value should be Array, assertion failed when the value is not an array.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotArray(Value actual,String msg)

The type of test value should not be Array, assertion failed when the value is an array.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isString(Value actual,String msg)

The type of test value should be String, assertion failed when the value is not a string.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotString(Value actual,String msg)

The type of test value should not be String, assertion failed when the value is a string.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNumber(Value actual,String msg)

The type of test value should be Number, assertion failed when the value is not a number.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotNumber(Value actual,String msg)

The type of test value should not be Number, assertion failed when the value is a number.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isBoolean(Value actual,String msg)

The type of test value should be Boolean, assertion failed when the value is not a boolean.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static isNotBoolean(Value actual,String msg)

The type of test value should not be Boolean, assertion failed when the value is a boolean.

Parameters

  • actual The value need to be tested.

  • msg The message of assertion failed when return false.

public static static typeOf(Value actual,String type,String msg)

The type of test value should be the specified one, assertion failed when the value type is not match.

Parameters

  • actual The value need to be tested.

  • type Specified type.

  • msg The message of assertion failed when return false.

public static static notTypeOf(Value actual,String type,String msg)

The type of test value should not be the specified one, assertion failed when the value type is match.

Parameters

  • actual The value need to be tested.

  • type Specified type.

  • msg The message of assertion failed when return false.

public static static property(Value object,Value prop,String msg)

The test value should contain the specified property, assertion failed when the property not be contained.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • msg The message of assertion failed when return false.

public static static notProperty(Value object,Value prop,String msg)

The test value should not contain the specified property, assertion failed when the property contained.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • msg The message of assertion failed when return false.

public static static deepProperty(Value object,Value prop,String msg)

The test value should deeply contain the specified property, assertion failed when the property not be contained.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • msg The message of assertion failed when return false.

public static static notDeepProperty(Value object,Value prop,String msg)

The test value should not deeply contain the specified property, assertion failed when the property contained.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • msg The message of assertion failed when return false.

public static static propertyVal(Value object,Value prop,Value value,String msg)

The specified property of test value should equal the given one, assertion failed when not match.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • value Given value

  • msg The message of assertion failed when return false.

public static static propertyNotVal(Value object,Value prop,Value value,String msg)

The specified property of test value should not equal the given one, assertion failed when match.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • value Given value

  • msg The message of assertion failed when return false.

public static static deepPropertyVal(Value object,Value prop,Value value,String msg)

The specified property of test value should deeply equal the given one, assertion failed when not match.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • value Given value

  • msg The message of assertion failed when return false.

public static static deepPropertyNotVal(Value object,Value prop,Value value,String msg)

The specified property of test value should not deeply equal the given one, assertion failed when match.

Parameters

  • object The object to be tested.

  • prop Property to be tested, fields terminated by '.'

  • value Given value

  • msg The message of assertion failed when return false.

public static static throws(Function block,String msg)

The block code should throw an error, assertion failed when not throw one.

Parameters

  • block The code need to be test that specified as function.

  • msg The message of assertion failed when return false.

public static static doesNotThrow(Function block,String msg)

The block code should not throw an error, assertion failed when throw one.

Parameters

  • block The code need to be test that specified as function.

  • msg The message of assertion failed when return false.

namespace base32

base32 module with encode and decode operations. to use:

var encoding = require('encoding');
var base32 = encoding.base32;

or:

var base32 = require('base32');

Summary

Members Descriptions
public static String encode(Buffer data) Encode buffer data to string with base32 format.
public static Buffer decode(String data) Decode string to binary data with base32 format.

Members

public static String encode(Buffer data)

Encode buffer data to string with base32 format.

Parameters

  • data Buffer data to be encoded.

Returns

The encoded result string.

public static Buffer decode(String data)

Decode string to binary data with base32 format.

Parameters

  • data String to be decoded.

Returns

The decoded result binary data.

namespace base64

base64 module with encode and decode operations. to use:

var encoding = require('encoding');
var base64 = encoding.base64;

or:

var base64 = require('base64');

Summary

Members Descriptions
public static String encode(Buffer data) Encode buffer data to string with base64 format.
public static Buffer decode(String data) Decode string to binary data with base64 format.

Members

public static String encode(Buffer data)

Encode buffer data to string with base64 format.

Parameters

  • data Buffer data to be encoded.

Returns

The encoded result string.

public static Buffer decode(String data)

Decode string to binary data with base64 format.

Parameters

  • data String to be decoded.

Returns

The decoded result binary data.

namespace base64vlq

base64vlq module with encode and decode operations. to use:

var encoding = require('encoding');
var base64vlq = encoding.base64vlq;

or:

var base64vlq = require('base64vlq');

Summary

Members Descriptions
public static String encode(Integer data) Encode int data to string with base64vlq format.
public static String encode(Array data) Encode array data to string with base64vlq format.
public static Array decode(String data) Decode string to binary data with base64vlq format.

Members

public static String encode(Integer data)

Encode int data to string with base64vlq format.

Parameters

  • data Int data to be encoded.

Returns

The encoded result string.

public static String encode(Array data)

Encode array data to string with base64vlq format.

Parameters

  • data Array data to be encoded.

Returns

The encoded result string.

public static Array decode(String data)

Decode string to binary data with base64vlq format.

Parameters

  • data String data to be decoded.

Returns

The decoded result binary data.

namespace bson

bson module with encode and decode operations. to use:

var encoding = require('encoding');
var bson = encoding.bson;

or:

var bson = require('bson');

Summary

Members Descriptions
public static Buffer encode(Object data) Encode object to binary data with bson format.
public static Object decode(Buffer data) Decode binary data to object with bson format.

Members

public static Buffer encode(Object data)

Encode object to binary data with bson format.

Parameters

  • data Object to be encoded.

Returns

The encoded result binary data.

public static Object decode(Buffer data)

Decode binary data to object with bson format.

Parameters

  • data Binary data to be decoded.

Returns

The decoded result object.

namespace console

console module

Global reference. Console can be used to log info, warnings and errors. Log can be trace on different device when initialized from config files for tracking. Console logs support formatted output, e.g.

console.log("%d + %d = %d", 100, 200, 100 + 200);
  • s - string

  • d - number, including initeger and numbers

  • j - output in JSON

  • %% - output '' character

Summary

Members Descriptions
public static static add(Array cfg) Batch add console output, supportted devices are console, syslog and file, maximum output number is 10.
public static static add(Value cfg) Add console output, supportted devices are console, syslog and file, maximum output number is 10.
public static static reset() initialize with default configuration, only output in console
public static static log(String fmt,...) Record INFO log, Equivalent to the info function.
public static static log(...) Record INFO log, Equivalent to the info function.
public static static debug(String fmt,...) Record DEBUG log.
public static static debug(...) Record DEBUG log.
public static static info(String fmt,...) Record INFO log, Equivalent to the log function.
public static static info(...) Record INFO log, Equivalent to the log function.
public static static notice(String fmt,...) Record NOTICE log.
public static static notice(...) Record NOTICE log.
public static static warn(String fmt,...) Record WARN log.
public static static warn(...) Record WARN log.
public static static error(String fmt,...) Record ERROR log.
public static static error(...) Record ERROR log.
public static static crit(String fmt,...) Record CRIT log.
public static static crit(...) Record CRIT log.
public static static alert(String fmt,...) Record ALERT log.
public static static alert(...) Record ALERT log.
public static static dir(Value obj) Output object in JSON format.
public static static time(String label) Start a timer.
public static static timeEnd(String label) Value of specified timer.
public static static trace(String label) Output the current used stack.
public static static assert(Value value,String msg) Assertion test, which will throw error when testing result is false.
public static static print(String fmt,...) Formatted text output to the console, the content will not be written to log system, and the output text does not wrap automatically, the output can output continuously.
public static static print(...) Formatted text output to the console, the content will not be written to log system, and the output text does not wrap automatically, the output can output continuously.
public static String readLine(String msg) Read the user input from the console.

Members

public static static add(Array cfg)

Batch add console output, supportted devices are console, syslog and file, maximum output number is 10.

Console can be configured to send program outputs and system errors to different devices, for collecting runtime information.

console.add(["console", {
   type: "syslog",
   levels: [console.INFO, console.ERROR]
}]);

Parameters

  • cfg An array of console log config

public static static add(Value cfg)

Add console output, supportted devices are console, syslog and file, maximum output number is 10.

Console can be configured to send program outputs and system errors to different devices, for collecting runtime information.

Cfg is config which can be set as the string of devices name.

console.add("console");

You can also configure console levels for one device

console.add({
   type: "console",
   levels: [console.INFO, console.ERROR]  // options, output all level of log if skip this option.
});

Syslog only works on posix platform:

console.add({
   type: "syslog",
   levels: [console.INFO, console.ERROR]
});

file log dose not support simple calls

console.add({
   type: "file",
   levels: [console.INFO, console.ERROR],
   path: "path/to/file",  // required
   split: "30m",  //optional, options can be "day", "hour", "minute", "###k", "###m", "###g"
   count: 10 //optional, options can be any integer between 2-128, this option requires the split option
});

Parameters

  • cfg Output configuration

public static static reset()

initialize with default configuration, only output in console

public static static log(String fmt,...)

Record INFO log, Equivalent to the info function.

Record the INFO level of log information. Typically used to output the non-erroneous message.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static log(...)

Record INFO log, Equivalent to the info function.

Record the INFO level of log information. Typically used to output the non-erroneous message.

Parameters

  • ... Optional parameter list

public static static debug(String fmt,...)

Record DEBUG log.

Record the DEBUG level of log information. Typically used to output the debug message.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static debug(...)

Record DEBUG log.

Record the DEBUG level of log information. Typically used to output the debug message.

Parameters

  • ... Optional parameter list

public static static info(String fmt,...)

Record INFO log, Equivalent to the log function.

Record the INFO level of log information. Typically used to output the non-erroneous message.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static info(...)

Record INFO log, Equivalent to the log function.

Record the INFO level of log information. Typically used to output the non-erroneous message.

Parameters

  • ... Optional parameter list

public static static notice(String fmt,...)

Record NOTICE log.

Record the NOTICE level of log information. Typically used to output the suggestive debug message.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static notice(...)

Record NOTICE log.

Record the NOTICE level of log information. Typically used to output the suggestive debug message.

Parameters

  • ... Optional parameter list

public static static warn(String fmt,...)

Record WARN log.

Record the WARN level of log information. Typically used to output the warning debug message. Important.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static warn(...)

Record WARN log.

Record the WARN level of log information. Typically used to output the warning debug message. Important.

Parameters

  • ... Optional parameter list

public static static error(String fmt,...)

Record ERROR log.

Record the ERROR level of log information. Typically used to output the error message. Very important. System error message is also record in this level.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static error(...)

Record ERROR log.

Record the ERROR level of log information. Typically used to output the error message. Very important. System error message is also record in this level.

Parameters

  • ... Optional parameter list

public static static crit(String fmt,...)

Record CRIT log.

Record the CRIT level of log information. Typically used to output the critical error message. Very important.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static crit(...)

Record CRIT log.

Record the CRIT level of log information. Typically used to output the critical error message. Very important.

Parameters

  • ... Optional parameter list

public static static alert(String fmt,...)

Record ALERT log.

Record the ALERT level of log information. Typically used to output the alert error message. Very important. This level is the highest one.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static alert(...)

Record ALERT log.

Record the ALERT level of log information. Typically used to output the alert error message. Very important. This level is the highest one.

Parameters

  • ... Optional parameter list

public static static dir(Value obj)

Output object in JSON format.

Parameters

  • obj The object given to display

public static static time(String label)

Start a timer.

Parameters

  • label Title, default is an empty string.

public static static timeEnd(String label)

Value of specified timer.

Parameters

  • label Title, default is an empty string.

public static static trace(String label)

Output the current used stack.

Output the current used stack by log.

Parameters

  • label Title, default is an empty string.

public static static assert(Value value,String msg)

Assertion test, which will throw error when testing result is false.

Parameters

  • value The value for test

  • msg Error message

public static static print(String fmt,...)

Formatted text output to the console, the content will not be written to log system, and the output text does not wrap automatically, the output can output continuously.

Parameters

  • fmt The format string

  • ... Optional parameter list

public static static print(...)

Formatted text output to the console, the content will not be written to log system, and the output text does not wrap automatically, the output can output continuously.

Parameters

  • ... Optional parameter list

public static String readLine(String msg)

Read the user input from the console.

Parameters

  • msg Prompt information

Returns

Returns the user input information.

namespace coroutine

Concurrency control module.

The way to use: var coroutine = require('coroutine');

Summary

Members Descriptions
public static Fiber start(Function func,...) Start a fibers and return the fiber Object.
public static Array parallel(Array funcs,Integer fibers) Execute a set of functions parallel, and wait for the return.
public static Array parallel(Array datas,Function func,Integer fibers) Execute a function deal with a set of data parallel, and wait for the return.
public static Array parallel(...) Execute a set of functions parallel, and wait for the return.
public static Fiber current() Returns the current fiber.
public static static sleep(Integer ms) Pause the current fiber specified time.

Members

public static Fiber start(Function func,...)

Start a fibers and return the fiber Object.

Parameters

  • func Set a function to be executed by the fibers.

  • ... Variable parameter sequence, the sequence will pass to function in fiber.

Returns

Returns the fiber object.

public static Array parallel(Array funcs,Integer fibers)

Execute a set of functions parallel, and wait for the return.

Parameters

  • funcs An array of function to be executed parallel

  • fibers Limit the number of concurrent fiber, default -1 (the number of funcs size).

Returns

Returns the array of functions execute results

public static Array parallel(Array datas,Function func,Integer fibers)

Execute a function deal with a set of data parallel, and wait for the return.

Parameters

  • datas An array of params to be executed by function parallel.

  • func The function executed parallel

  • fibers Limit the number of concurrent fiber, default -1 (the number of datas size).

Returns

Returns the array of function execute results

public static Array parallel(...)

Execute a set of functions parallel, and wait for the return.

Parameters

  • ... A set of function to be execute parallel

Returns

Returns the array of functions execute results

public static Fiber current()

Returns the current fiber.

Returns

Returns the current fiber object.

public static static sleep(Integer ms)

Pause the current fiber specified time.

Parameters

  • ms Specify the suspend time in milliseconds, the default value is 0, which back to resume immediately.

namespace crypto

Encryption algorithm module.

The way to use:

var crypto = require('crypto');

Summary

Members Descriptions
public static PKey loadPKey(String filename,String password) Load a PEM/DER format key file.
public static X509Cert loadCert(String filename) Load a CRT/PEM/DER/TXT format certificate can be called multiple times.
public static X509Crl loadCrl(String filename) Load a PEM/DER format revoked certificate can be called multiple times.
public static X509Req loadReq(String filename) Load a PEM/DER format requested certificate can be called multiple times.
public static Buffer randomBytes(Integer size) Generate the specified size of the random number, which use the havege generator.
public static Buffer pseudoRandomBytes(Integer size) Generate the specified size of the pseudo-random number, which use the entropy generator.
public static String randomArt(Buffer data,String title,Integer size) Generate a visual character image by use given data.

Members

public static PKey loadPKey(String filename,String password)

Load a PEM/DER format key file.

Parameters

  • filename Key file name.

  • password Decryption password.

public static X509Cert loadCert(String filename)

Load a CRT/PEM/DER/TXT format certificate can be called multiple times.

LoadFile load mozilla certdata.txt, which can be download from http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt

Parameters

  • filename Certificate file name.

public static X509Crl loadCrl(String filename)

Load a PEM/DER format revoked certificate can be called multiple times.

Parameters

  • filename The cancellation certificate file name.

public static X509Req loadReq(String filename)

Load a PEM/DER format requested certificate can be called multiple times.

Parameters

  • filename The requested certificate file name.

public static Buffer randomBytes(Integer size)

Generate the specified size of the random number, which use the havege generator.

Parameters

  • size Specify the size of the generated random number.

Returns

Return the generated random number.

public static Buffer pseudoRandomBytes(Integer size)

Generate the specified size of the pseudo-random number, which use the entropy generator.

Parameters

  • size Specify the size of the generated random number.

Returns

Return the generated random number.

public static String randomArt(Buffer data,String title,Integer size)

Generate a visual character image by use given data.

Parameters

  • data Specifies the data to display.

  • title The title of the specified character image, multibyte characters can cause width error.

  • size The character image size.

Returns

Return the generated visual string image.

namespace db

Database access module.

Basic module for create database and database operation, The way to use::

var db = require('db');

Summary

Members Descriptions
public static object open(String connString) This method offer a general entrance to open a database, call different engines according to the providing connString.
public static MySQL openMySQL(String connString) Open a mysql database.
public static SQLite openSQLite(String connString) Open a sqlite database.
public static MongoDB openMongoDB(String connString) Open a mongodb database.
public static LevelDB openLevelDB(String connString) Open a leveldb database.
public static Redis openRedis(String connString) Open a Redis database.
public static String format(String sql,...) Formatting a sql command, and returns the formatted results.
public static String formatMySQL(String sql,...) Formatting a sql command, and returns the formatted results.
public static String escape(String str,Boolean mysql) String encoded as security coded SQL strings.

Members

public static object open(String connString)

This method offer a general entrance to open a database, call different engines according to the providing connString.

Parameters

  • connString Database Description, For example: mysql://user:pass@host/db

Returns

Returns the database connection object.

public static MySQL openMySQL(String connString)

Open a mysql database.

Parameters

  • connString Database Description, For example: mysql://user:pass@host/db

Returns

Returns the database connection object.

public static SQLite openSQLite(String connString)

Open a sqlite database.

Parameters

  • connString Database Description, For example: sqlite:test.db or test.db

Returns

Returns the database connection object.

public static MongoDB openMongoDB(String connString)

Open a mongodb database.

Parameters

  • connString Database Description

Returns

Returns the database connection object.

public static LevelDB openLevelDB(String connString)

Open a leveldb database.

Parameters

  • connString Database Description, For example: level:test.db or test.db

Returns

Returns the database connection object.

public static Redis openRedis(String connString)

Open a Redis database.

Parameters

  • connString Database Description, For example: redis://server:port or "server"

Returns

Returns the database connection object.

public static String format(String sql,...)

Formatting a sql command, and returns the formatted results.

Parameters

  • sql Format string, optional parameters can be specified as '?', for example: 'SELECT FROM TEST WHERE [id]=?'

  • ... Optional parameter list

Returns

Return the formatted sql command.

public static String formatMySQL(String sql,...)

Formatting a sql command, and returns the formatted results.

Parameters

  • sql Format string, optional parameters can be specified as '?', for example: 'SELECT FROM TEST WHERE [id]=?'

  • ... Optional parameter list

Returns

Return the formatted sql command.

public static String escape(String str,Boolean mysql)

String encoded as security coded SQL strings.

Parameters

  • str The string that need to be encoded

  • mysql Specify the Mysql encoding, the default value is false

Returns

Returns the encoded string

namespace encoding

module with encode and decode operations between hex and other format data. to use:

var encoding = require('encoding');

Summary

Members Descriptions
public static String jsstr(String str,Boolean json) Encode the string to Javascript escaped string that can be contained in the javascript code.
public static String encodeURI(String url) Url encoding.
public static String encodeURIComponent(String url) Url component encoding.
public static String decodeURI(String url) Url decoding.

Members

public static String jsstr(String str,Boolean json)

Encode the string to Javascript escaped string that can be contained in the javascript code.

Parameters

  • str The string to encode

  • json Specifies generate the string json compatible.

Returns

Returns the encoded string.

public static String encodeURI(String url)

Url encoding.

Parameters

  • url Url to be encoded.

Returns

The encoded result string.

public static String encodeURIComponent(String url)

Url component encoding.

Parameters

  • url Url to be encoded.

Returns

The encoded result string.

public static String decodeURI(String url)

Url decoding.

Parameters

  • url Url to be decoded.

Returns

The decoded result string.

namespace fs

file system module

how to use

var fs = require('fs');

Summary

Members Descriptions
public static Boolean exists(String path) search if the file or directory exists
public static Boolean existsSync(String path) search if the file or directory exists. Sync version of fs.exists().
public static static unlink(String path) the file you want to delete
public static static unlinkSync(String path) the file you want to delete. Sync version of fs.unlink().
public static static mkdir(String path,Integer mode) create a directory
public static static mkdirSync(String path,Integer mode) create a directory. Sync version of fs.mkdir().
public static static rmdir(String path) delete a directory
public static static rmdirSync(String path) delete a directory. Sync version of fs.rmdir().
public static static rename(String from,String to) rename a file
public static static renameSync(String from,String to) rename a file
public static static copy(String from,String to) copy file
public static static chmod(String path,Integer mode) check the permission of targeting file, Windows does not support this
public static static chmodSync(String path,Integer mode) check the permission of targeting file, Windows does not support this. Sync version of fs.chmod().
public static Stat stat(String path) check file basic infomation/stat
public static Stat statSync(String path) check file basic infomation/stat. Sync version of fs.stat().
public static List readdir(String path) read fileinfo inside target directory
public static List readdirSync(String path) read fileinfo inside target directory. Sync version of fs.readdir().
public static SeekableStream open(String fname,String flags) open text file to read, write, or read and write
public static SeekableStream openSync(String fname,String flags) open text file to read, write, or read and write. Sync version of fs.open().
public static BufferedStream openTextStream(String fname,String flags) open text file to read, write, or read and write
public static String readTextFile(String fname) open file and read the conent.
public static String readFile(String fname) open a file, read the content
public static Buffer readFileSync(String fname) open a file, read the content. Sync version of fs.readFile().
public static Array readLines(String fname,Integer maxlines) open file, ready each line of text content intot an array, end of line is recognized based on EOL definition, by default, posix system: "\n"; windows system: "\r\n"
public static static writeTextFile(String fname,String txt) create text file and write to file 创建文本文件,并写入内容
public static static writeFile(String fname,String txt) create file, and write new content
public static static writeFileSync(String fname,Buffer data) create file, and write new content. Sync version of fs.writeFile().

Members

public static Boolean exists(String path)

search if the file or directory exists

Parameters

  • path assign the search path

Returns

return True indicates the file or directory exists

public static Boolean existsSync(String path)

search if the file or directory exists. Sync version of fs.exists().

Parameters

  • path assign the search path

Returns

return True indicates the file or directory exists

public static static unlink(String path)

the file you want to delete

Parameters

  • path the path you want to delete

public static static unlinkSync(String path)

the file you want to delete. Sync version of fs.unlink().

Parameters

  • path the path you want to delete

public static static mkdir(String path,Integer mode)

create a directory

Parameters

  • path assign the name of directory

  • mode assign file ownership, Windows user ignore this

public static static mkdirSync(String path,Integer mode)

create a directory. Sync version of fs.mkdir().

Parameters

  • path assign the name of directory

  • mode assign file ownership, Windows user ignore this

public static static rmdir(String path)

delete a directory

Parameters

  • path the name of targeting directory

public static static rmdirSync(String path)

delete a directory. Sync version of fs.rmdir().

Parameters

  • path the name of targeting directory

public static static rename(String from,String to)

rename a file

Parameters

  • from the targeting file name

  • to the name you want to change to

public static static renameSync(String from,String to)

rename a file

Parameters

  • from the targeting file name. Sync version of fs.rename().

  • to the name you want to change to

public static static copy(String from,String to)

copy file

Parameters

  • from file path

  • to new file path

public static static chmod(String path,Integer mode)

check the permission of targeting file, Windows does not support this

Parameters

  • path the path to the targeting file

  • mode targeting file permission

public static static chmodSync(String path,Integer mode)

check the permission of targeting file, Windows does not support this. Sync version of fs.chmod().

Parameters

  • path the path to the targeting file

  • mode targeting file permission

public static Stat stat(String path)

check file basic infomation/stat

Parameters

  • path the path to the targeting file

Returns

return file basic infomation/stat

public static Stat statSync(String path)

check file basic infomation/stat. Sync version of fs.stat().

Parameters

  • path the path to the targeting file

Returns

return file basic infomation/stat

public static List readdir(String path)

read fileinfo inside target directory

Parameters

  • path the path to the directory

Returns

return a array of files' info in target directory

public static List readdirSync(String path)

read fileinfo inside target directory. Sync version of fs.readdir().

Parameters

  • path the path to the directory

Returns

return a array of files' info in target directory

public static SeekableStream open(String fname,String flags)

open text file to read, write, or read and write

Parameters

  • fname the name of file

  • flags define the method for opening file, default is 'r', read only, other supported methods see below:

  • 'r' ready only, throw excption if file dose not exists

  • 'r+' read and write, throw excption if file dose not exists

  • 'w' write only, create new if file dose not exist, othewise overwrite

  • 'w+' ready and write, create new if file dose not exist, othewise overwrite

  • 'a' write only add file, create new if file dose not exist, othewise overwrite

  • 'a+' read and write to add file, create new if file dose not exist, othewise overwrite

Returns

return opened file object

public static SeekableStream openSync(String fname,String flags)

open text file to read, write, or read and write. Sync version of fs.open().

Parameters

  • fname the name of file

  • flags define the method for opening file, default is 'r', read only, other supported methods see below:

  • 'r' ready only, throw excption if file dose not exists

  • 'r+' read and write, throw excption if file dose not exists

  • 'w' write only, create new if file dose not exist, othewise overwrite

  • 'w+' ready and write, create new if file dose not exist, othewise overwrite

  • 'a' write only add file, create new if file dose not exist, othewise overwrite

  • 'a+' read and write to add file, create new if file dose not exist, othewise overwrite

Returns

return opened file object

public static BufferedStream openTextStream(String fname,String flags)

open text file to read, write, or read and write

Parameters

  • fname the name of file

  • flags define the method for opening file, default is 'r', read only, other supported methods see below:

  • 'r' ready only, throw excption if file dose not exists

  • 'r+' read and write, throw excption if file dose not exists

  • 'w' write only, create new if file dose not exist, othewise overwrite

  • 'w+' ready and write, create new if file dose not exist, othewise overwrite

  • 'a' write only add file, create new if file dose not exist, othewise overwrite

  • 'a+' read and write to add file, create new if file dose not exist, othewise overwrite

Returns

return opened file object

public static String readTextFile(String fname)

open file and read the conent.

Parameters

  • fname the name of file

Returns

file content

public static String readFile(String fname)

open a file, read the content

Parameters

  • fname assign file name

Returns

return content of opened file

public static Buffer readFileSync(String fname)

open a file, read the content. Sync version of fs.readFile().

Parameters

  • fname assign file name

Returns

return content of opened file

public static Array readLines(String fname,Integer maxlines)

open file, ready each line of text content intot an array, end of line is recognized based on EOL definition, by default, posix system: "\n"; windows system: "\r\n"

Parameters

  • fname assign file name

  • maxlines define the maximum number of line to read, read all lines by default

Returns

return the array containing every line of file content, if no content or connection is lost, then return an empty array

public static static writeTextFile(String fname,String txt)

create text file and write to file 创建文本文件,并写入内容

Parameters

  • fname assign file name

  • txt sting to be written

public static static writeFile(String fname,String txt)

create file, and write new content

Parameters

  • fname assign file name

  • txt the content you are going to write into file

public static static writeFileSync(String fname,Buffer data)

create file, and write new content. Sync version of fs.writeFile().

Parameters

  • fname assign file name

  • txt the content you are going to write into file

namespace gd

Image processing module.

Base module. It can be used to create and manipulate image files. The way to use:

var gd = require('gd');

Summary

Members Descriptions
public static Image create(Integer width,Integer height,Integer color) Create a new image.
public static Image load(Buffer data) Decoded image from the format data.
public static Image load(SeekableStream stm) Decoded image from the stream object.
public static Image load(String fname) Decoded image from the specified file.
public static Integer rgb(Integer red,Integer green,Integer blue) Generating a combined color through rgb color components.
public static Integer rgba(Integer red,Integer green,Integer blue,Number alpha) Generating a combined color through rgba color components.
public static Integer hsl(Number hue,Number saturation,Number lightness) Generating a combined color through hsl color components.
public static Integer hsla(Number hue,Number saturation,Number lightness,Number alpha) Generating a combined color through hsla color components.
public static Integer hsb(Number hue,Number saturation,Number brightness) Generating a combined color through hsb color components.
public static Integer hsba(Number hue,Number saturation,Number brightness,Number alpha) Generating a combined color through hsba color components.
public static Integer color(String color) Generating a combined color by string.

Members

public static Image create(Integer width,Integer height,Integer color)

Create a new image.

Parameters

  • width Specifies the width of the image.

  • height Specifies the height of the image.

  • color Specify the image type, the allowable value is gd.TRUECOLOR or gd.PALETTE

Returns

Returns the created image object of success.

public static Image load(Buffer data)

Decoded image from the format data.

Parameters

  • data The image data need decoded.

Returns

Return successfully decoded image object.

public static Image load(SeekableStream stm)

Decoded image from the stream object.

Parameters

  • stm The stream object of the specified image data.

Returns

Return successfully decoded image object.

public static Image load(String fname)

Decoded image from the specified file.

Parameters

  • fname Specify the file name.

Returns

Return successfully decoded image object.

public static Integer rgb(Integer red,Integer green,Integer blue)

Generating a combined color through rgb color components.

Parameters

  • red Red component in the range of 0-255

  • green Green component in the range of 0-255

  • blue Blue component in the range of 0-255

Returns

Returns the combined color.

public static Integer rgba(Integer red,Integer green,Integer blue,Number alpha)

Generating a combined color through rgba color components.

Parameters

  • red Red component in the range of 0-255

  • green Green component in the range of 0-255

  • blue Blue component in the range of 0-255

  • alpha Transparent component in the range of 0.0-1.0

Returns

Returns the combined color.

public static Integer hsl(Number hue,Number saturation,Number lightness)

Generating a combined color through hsl color components.

Parameters

  • hue Hue component in the range of 0-360.

  • saturation Saturation components in the range of 0.0-1.0

  • lightness Lightness component in the range of 0.0-1.0

Returns

Returns the combined color.

public static Integer hsla(Number hue,Number saturation,Number lightness,Number alpha)

Generating a combined color through hsla color components.

Parameters

  • hue Hue component in the range of 0-360.

  • saturation Saturation components in the range of 0.0-1.0

  • lightness Lightness component in the range of 0.0-1.0

  • alpha Transparent component in the range of 0.0-1.0

Returns

Returns the combined color.

public static Integer hsb(Number hue,Number saturation,Number brightness)

Generating a combined color through hsb color components.

Parameters

  • hue Hue component in the range of 0-360.

  • saturation Saturation components in the range of 0.0-1.0

  • brightness Brightness component in the range of 0.0-1.0

Returns

Returns the combined color.

public static Integer hsba(Number hue,Number saturation,Number brightness,Number alpha)

Generating a combined color through hsba color components.

Parameters

  • hue Hue component in the range of 0-360.

  • saturation Saturation components in the range of 0.0-1.0

  • brightness Brightness component in the range of 0.0-1.0

  • alpha Transparent component in the range of 0.0-1.0

Returns

Returns the combined color.

public static Integer color(String color)

Generating a combined color by string.

Parameters

  • color The specified color string, e.g: "#ff0000", "ff0000", "#f00", "f00"

Returns

Returns the combined color.

namespace global

Global object, which can be accessed by all scripts.

Summary

Members Descriptions
public static static run(String fname,Array argv) Run a script.
public static Value require(String id) Load a module and return module object, reference Module Management.
public static static GC() Mandatory for garbage collection.
public static static repl(Array cmds) Enter the interactive mode, you can interactively execute the internal commands and code which can only be referenced when js start.
public static static repl(Stream out,Array cmds) Enter the interactive mode, you can interactively execute the internal commands and code which can only be referenced when js start.

Members

public static static run(String fname,Array argv)

Run a script.

Parameters

  • fname Specifies the running path for script

  • argv Specify the run parameters, which can be caught in script by argv.

public static Value require(String id)

Load a module and return module object, reference Module Management.

require can be used to load the base module, such as file module.

Base module is initializing when the sandbox created, only need pass the id when referencing, e.g: require("net")。

File module is user-defined modules which required by the relative path beginning with './' or '../'. File module supports .js and .json file.

File module also supports the format package.json, system will first require the main in package.json when the module is a directory, then will try to load index.js or index.json in the path if failed.

If the path is not a reference beginning with ./ or ../, and the module is not non-base module, system will first require the match one in startup path, and then look for the .modules in current path, then try the parent directory.

Parameters

  • id Specifies the name of module to load

Returns

Returns the derivation of the load module

public static static GC()

Mandatory for garbage collection.

public static static repl(Array cmds)

Enter the interactive mode, you can interactively execute the internal commands and code which can only be referenced when js start.

Parameters

  • cmds Add commands in the following format:
[
    {
        cmd: ".test",
        help: "this is a test",
        exec: function(argv) {
            console.log(argv);
        }
    },
    {
        cmd: ".test1",
        help: "this is an other test",
        exec: function(argv) {
            console.log(argv);
        }
    }
]

public static static repl(Stream out,Array cmds)

Enter the interactive mode, you can interactively execute the internal commands and code which can only be referenced when js start.

At the same time allowed only a Stream repl, close the previous one when create a new Stream repl.

Parameters

  • out Input/output stream object, usually for a network connection

  • cmds Add commands in the following format:

[
    {
        cmd: ".test",
        help: "this is a test",
        exec: function(argv) {
            console.log(argv);
        }
    },
    {
        cmd: ".test1",
        help: "this is an other test",
        exec: function(argv) {
            console.log(argv);
        }
    }
]

namespace hash

Message digest calculation module, can be used to calculate the message digest and summary Signature.

Summary

Members Descriptions
public static Digest digest(Integer algo,Buffer data) Create a message digest object with the specified algorithm.
public static Digest digest(Integer algo) Create a message digest object with the specified algorithm.
public static Digest md2(Buffer data) Create a MD2 message digest object.
public static Digest md4(Buffer data) Create a MD4 message digest object.
public static Digest md5(Buffer data) Create a MD5 message digest object.
public static Digest sha1(Buffer data) Create a SHA1 message digest object.
public static Digest sha224(Buffer data) Create a SHA224 message digest object.
public static Digest sha256(Buffer data) Create a SHA256 message digest object.
public static Digest sha384(Buffer data) Create a SHA384 message digest object.
public static Digest sha512(Buffer data) Create a SHA512 message digest object.
public static Digest ripemd160(Buffer data) Create a RIPEMD160 message digest object.
public static Digest hmac(Integer algo,Buffer key) Create a message signature digest object with the specified algorithm.
public static Digest hmac_md2(Buffer key) Create a MD2 message digest signature object.
public static Digest hmac_md4(Buffer key) Create a MD4 message digest signature object.
public static Digest hmac_md5(Buffer key) Create a MD5 message digest signature object.
public static Digest hmac_sha1(Buffer key) Create a SHA1 message digest signature object.
public static Digest hmac_sha224(Buffer key) Create a SHA224 message digest signature object.
public static Digest hmac_sha256(Buffer key) Create a SHA256 message digest signature object.
public static Digest hmac_sha384(Buffer key) Create a SHA384 message digest signature object.
public static Digest hmac_sha512(Buffer key) Create a SHA512 message digest signature object.
public static Digest hmac_ripemd160(Buffer key) Create a RIPEMD160 message digest signature object.

Members

public static Digest digest(Integer algo,Buffer data)

Create a message digest object with the specified algorithm.

Parameters

  • algo Specifies the digest algorithm.

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest digest(Integer algo)

Create a message digest object with the specified algorithm.

Parameters

  • algo Specifies the digest algorithm.

Returns

Returns the message digest object.

public static Digest md2(Buffer data)

Create a MD2 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest md4(Buffer data)

Create a MD4 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest md5(Buffer data)

Create a MD5 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest sha1(Buffer data)

Create a SHA1 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest sha224(Buffer data)

Create a SHA224 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest sha256(Buffer data)

Create a SHA256 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest sha384(Buffer data)

Create a SHA384 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest sha512(Buffer data)

Create a SHA512 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest ripemd160(Buffer data)

Create a RIPEMD160 message digest object.

Parameters

  • data Binary data needs to be updated.

Returns

Returns the message digest object.

public static Digest hmac(Integer algo,Buffer key)

Create a message signature digest object with the specified algorithm.

Parameters

  • algo Specifies the digest algorithm.

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_md2(Buffer key)

Create a MD2 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_md4(Buffer key)

Create a MD4 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_md5(Buffer key)

Create a MD5 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_sha1(Buffer key)

Create a SHA1 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_sha224(Buffer key)

Create a SHA224 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_sha256(Buffer key)

Create a SHA256 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_sha384(Buffer key)

Create a SHA384 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_sha512(Buffer key)

Create a SHA512 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

public static Digest hmac_ripemd160(Buffer key)

Create a RIPEMD160 message digest signature object.

Parameters

  • key Binary signature key.

Returns

Returns the message digest object.

namespace hex

module with encode and decode operations between hex and string. to use:

var encoding = require('encoding');
var hex = encoding.hex;

or:

var hex = require('hex');

Summary

Members Descriptions
public static String encode(Buffer data) Encode data whith hex format.
public static Buffer decode(String data) Decode string to binary data with hex format.

Members

public static String encode(Buffer data)

Encode data whith hex format.

Parameters

  • data Data to be encoded.

Returns

Encoded result string.

public static Buffer decode(String data)

Decode string to binary data with hex format.

Parameters

  • data String to be decode.

Returns

Decoded binary data result.

namespace http

HTTP transfer protocol module, handels http protocol.

Summary

Members Descriptions
public static HttpRequestnewRequest() create a http request object,reference HttpRequest
public static HttpResponsenewResponse() create a http response object,reference HttpResponse
public static HttpCookienewCookie() create a http cookie object,reference HttpCookie
public static HttpServernewServer() create a http server,reference HttpServer
public static HttpsServernewHttpsServer() create a https server, reference HttpsServer
public static HttpHandlernewHandler() create a http protocol handler,reference HttpHandler
public static Handler fileHandler(String root,Object mimes) create a http static file processor, in case of using static file to respond http request
public static HttpResponse request(Stream conn,HttpRequest req) send http request to connection object,return response
public static HttpResponse request(String method,String url,Object headers) assign requested url, and return
public static HttpResponse request(String method,String url,SeekableStream body,Object headers) Request the specified url, and get the response.
public static HttpResponse request(String method,String url,SeekableStream body,Map headers) Request the specified url, and get the response.
public static HttpResponse request(String method,String url,Buffer body,Object headers) Request the specified url, and get the response.
public static HttpResponse get(String url,Object headers) reuqest url with GET method,and return response,same as request("GET", ...)
public static HttpResponse post(String url,SeekableStream body,Object headers) reuqest url with POST method,and return response,same as request("POST", ...)
public static HttpResponse post(String url,Buffer body,Object headers) reuqest url with POST method,and return response,same as request("POST", ...)

Members

public static HttpRequestnewRequest()

create a http request object,reference HttpRequest

public static HttpResponsenewResponse()

create a http response object,reference HttpResponse

public static HttpCookienewCookie()

create a http cookie object,reference HttpCookie

public static HttpServernewServer()

create a http server,reference HttpServer

public static HttpsServernewHttpsServer()

create a https server, reference HttpsServer

public static HttpHandlernewHandler()

create a http protocol handler,reference HttpHandler

public static Handler fileHandler(String root,Object mimes)

create a http static file processor, in case of using static file to respond http request

Parameters

  • root file root folder

  • mimes extends mime settings

  • mimes extedns mime settings

Returns

return a static file processor to handle http request

fileHandler support gzip pre-compression,when accept gzip in content-typeand filename.ext.gz exists under same root,then return the file directly, to avoid extra load on server.

public static HttpResponse request(Stream conn,HttpRequest req)

send http request to connection object,return response

Parameters

  • conn assign requested connection object

  • req the HttpRequest obejct need to be sent

Returns

return server response

public static HttpResponse request(String method,String url,Object headers)

assign requested url, and return

Parameters

  • method define http request method, such as: GET, POST

  • url assigned url,has to be full url with root path

  • headers define http request header,default is None

Returns

reutrn server response

public static HttpResponse request(String method,String url,SeekableStream body,Object headers)

Request the specified url, and get the response.

Parameters

  • method define http method, such as: GET, POST

  • url assigned url,has to be full url with root path

  • body define http body content

  • headers define http request header,default is None

Returns

reutrn server response

public static HttpResponse request(String method,String url,SeekableStream body,Map headers)

Request the specified url, and get the response.

Parameters

  • method define http method, such as: GET, POST

  • url assigned url,has to be full url with root path

  • body define http body content

  • headers define http request header, default is None

Returns

reutrn server response

public static HttpResponse request(String method,String url,Buffer body,Object headers)

Request the specified url, and get the response.

Parameters

  • method define http method, such as: GET, POST

  • url assigned url,has to be full url with root path

  • body define http body content

  • headers define http request header, default is None

Returns

reutrn server response

public static HttpResponse get(String url,Object headers)

reuqest url with GET method,and return response,same as request("GET", ...)

Parameters

  • url assigned url,has to be full url with root path

  • headers define http request header,default is None

Returns

reutrn server response

public static HttpResponse post(String url,SeekableStream body,Object headers)

reuqest url with POST method,and return response,same as request("POST", ...)

Parameters

  • url assigned url,has to be full url with root path

  • body define http body content

  • headers define http request header,default is None

Returns

reutrn server response

public static HttpResponse post(String url,Buffer body,Object headers)

reuqest url with POST method,and return response,same as request("POST", ...)

Parameters

  • url assigned url,has to be full url with root path

  • body define http body content

  • headers define http request header,default is None

Returns

reutrn server response

namespace iconv

iconv Module with encode and decode operations between text and binary. to use:

var encoding = require('encoding');
var iconv = encoding.iconv;

or:

var iconv = require('iconv');

Summary

Members Descriptions
public static Buffer encode(String charset,String data) Convert text to binary with iconv.
public static String decode(String charset,Buffer data) Convert binary to text with iconv.

Members

public static Buffer encode(String charset,String data)

Convert text to binary with iconv.

Parameters

  • charset The charset to be use.

  • data The text to be converted.

Returns

The binary encoded result.

public static String decode(String charset,Buffer data)

Convert binary to text with iconv.

Parameters

  • charset The charset to be use.

  • data Binary to be converted.

Returns

The text decoded result.

namespace io

IO module.

To use it:

var io = require('io');

Summary

Members Descriptions
public static MemoryStreamnewMemoryStream() Create a memory stream, see MemoryStream.
public static BufferedStreamnewBufferedStream() Create a buffered read stream, see BufferedStream.

Members

public static MemoryStreamnewMemoryStream()

Create a memory stream, see MemoryStream.

public static BufferedStreamnewBufferedStream()

Create a buffered read stream, see BufferedStream.

namespace json

json module with encode and decode operations. to use:

var encoding = require('encoding');
var json = encoding.json;

or:

var json = require('json');

Summary

Members Descriptions
public static String encode(Value data) Encode a json variable to string with json format.
public static Value decode(String data) Decode a string variable to json with json format.

Members

public static String encode(Value data)

Encode a json variable to string with json format.

Parameters

  • data Value to be encoded.

Returns

The encoded string result.

public static Value decode(String data)

Decode a string variable to json with json format.

Parameters

  • data String to be decoded.

Returns

Json value decoded result.

namespace mq

Message queue module.

Summary

Members Descriptions
public static Handler jsHandler(Value hdlr) Create a javascript message handler, return immediately when pass by value.
public static AsyncWait await() Create async handler.
public static Handler nullHandler() Create a empty handler.
public static static invoke(Handler hdlr,object v) Invoke a message or object to given handler.

Members

public static Handler jsHandler(Value hdlr)

Create a javascript message handler, return immediately when pass by value.

Parameters

  • hdlr builtin handler, function or javascript mapping object, handler will map be mapped automatically

Returns

Return handler of handle function

Syntax:

function func(v){
}

Parameter v is the message to procee, there are three possibilities:

  • Object javascript object, used for mapping message

  • Function javascript function, used for next stage

  • Handler Builtin handler for next stage No return or other result will finish message processing.

Use message mapping handler to handle nested logic as follows:

hdlr = mq.jsHandler({
    // fun1
   fun1 : function(v){},
   sub : {
       // sub.fun2 or sub/fun2
       fun2 : function(v){},
       // sub.hdlr or sub/hdlr
       hdlr: myHandler
   }
});

In the example, fun1 and fun2 are normal javascript handle function, sub is a sub-object, myHandler is a handler

public static AsyncWait await()

Create async handler.

Returns

Return created handler

Wait handler async as follows:

function func(v){
    var await = mq.await();

    call_some_async_func(v1, v2, v3, function() {
            await.end();
        });

    return await;
}

Example uses javascript message handle function, when it returns, message handle engine will wait for await until await.end being called.

public static Handler nullHandler()

Create a empty handler.

Returns

Return empry handler

public static static invoke(Handler hdlr,object v)

Invoke a message or object to given handler.

Parameters

Unlike invoke method of handler, this will loop and wait every handler until reach null

namespace net

Network module.

Used for create and operate netwrok resource, to use it:

var net = require('net');

Summary

Members Descriptions
public static String resolve(String name,Integer family) Resolve address of given host.
public static String ip(String name) Quick query host address, same as resolve(name)
public static String ipv6(String name) Quick query host ipv6 address, same as resolve(name, net.AF_INET6)
public static Stream connect(String host,Integer port,Integer family) Create a Socket object and make connection, see Socket.
public static Stream connect(String url) Create a Socket or SslSocket and make connection.
public static Smtp openSmtp(String host,Integer port,Integer family) Create a Smtp object and make connection, see Smtp.
public static String backend() Get system backend async network engine.

Members

public static String resolve(String name,Integer family)

Resolve address of given host.

Parameters

  • name Home name

  • family Return type, default is AF_INET

Returns

Return IP result string

public static String ip(String name)

Quick query host address, same as resolve(name)

Parameters

  • name Host name

Returns

Return IP result string

public static String ipv6(String name)

Quick query host ipv6 address, same as resolve(name, net.AF_INET6)

Parameters

  • name Host name

Returns

Return IPv6 result string

public static Stream connect(String host,Integer port,Integer family)

Create a Socket object and make connection, see Socket.

Parameters

  • host Target address or host name

  • port Target port number

  • family Addree type, default is AF_INE, ipv4

Returns

Return connected Socket object

public static Stream connect(String url)

Create a Socket or SslSocket and make connection.

Parameters

  • url URL with protocol, can be tcp://host:port or ssl://host:port

Returns

Return connected Socket or SslSocket object

public static Smtp openSmtp(String host,Integer port,Integer family)

Create a Smtp object and make connection, see Smtp.

Parameters

  • host Target address or host name

  • port Target port number

  • family Addree type, default is AF_INE, ipv4

Returns

Return connected Smtp object

public static String backend()

Get system backend async network engine.

Returns

Return network engine name

namespace os

Operating system and file system module.

To use it:

var os = require('os');

Summary

Members Descriptions
public static Number uptime() Get operating system time in seconds.
public static Array loadavg() Get system load average, 1, 5 and 15 minutes.
public static Long totalmem() Get system total memory in bytes.
public static Long freemem() Get system free memory in bytes.
public static Array CPUInfo() Get system CPU number and information.
public static Integer CPUs() Get system CPU number.
public static Object networkInfo() Get system network information.
public static Date time(String tmString) Parse or get system time.
public static Date dateAdd(Date d,Integer num,String part) Time calculation function, use part to indicate time.
public static Object memoryUsage() Get current memory usage.

Members

public static Number uptime()

Get operating system time in seconds.

Returns

Return time in integer

public static Array loadavg()

Get system load average, 1, 5 and 15 minutes.

Returns

Return results array

public static Long totalmem()

Get system total memory in bytes.

Returns

Return total memory

public static Long freemem()

Get system free memory in bytes.

Returns

Return free memory

public static Array CPUInfo()

Get system CPU number and information.

Returns

Return CPU information array

public static Integer CPUs()

Get system CPU number.

Returns

Return CPU number

public static Object networkInfo()

Get system network information.

Returns

Return network information

public static Date time(String tmString)

Parse or get system time.

Parameters

  • tmString Time format, default is query current time

Returns

Return javascript Date object

public static Date dateAdd(Date d,Integer num,String part)

Time calculation function, use part to indicate time.

Parameters

  • d Date object to calculate on

  • num Number to calculate

  • part Type to calculate, can be "year", "month", "day", "hour", "minute", "second"

Returns

Return javascript Date object

public static Object memoryUsage()

Get current memory usage.

Returns

Return memory usage

Usage includes:

{
  "rss": 8622080,
  "heapTotal": 4083456,
  "heapUsed": 1621800,
  "nativeObjects": 122
}

Notes:

  • rss Physical memory being occupied by current process

  • heapTotal Return v8 engine heap memory size

  • heapUsed Return v8 engine heap memory size in use

  • nativeObjects Return number of memory objects

namespace path

File path module.

To use it:

var path = require('path');

Summary

Members Descriptions
public static String normalize(String path) Normalize path.
public static String basename(String path,String ext) Get file name in path, ignore extension with file has it.
public static String extname(String path) Get file extension.
public static String dirname(String path) Get directory in path.
public static String fullpath(String path) Get full path.
public static String join(...) Merge multiple paths to a single relative path.
public static String resolve(...) Merge multiple paths to a single absolute path.

Members

public static String normalize(String path)

Normalize path.

Parameters

  • path Original path

Returns

Return normalized path

public static String basename(String path,String ext)

Get file name in path, ignore extension with file has it.

Parameters

  • path Original path

  • ext Given extension

Returns

Return file name

public static String extname(String path)

Get file extension.

Parameters

  • path Original path

Returns

Return file extension

public static String dirname(String path)

Get directory in path.

Parameters

  • path Original path

Returns

Return directory

public static String fullpath(String path)

Get full path.

Parameters

  • path Original path

Returns

Return full path

public static String join(...)

Merge multiple paths to a single relative path.

Parameters

  • ... One or more relative paths

Returns

Return new relative path

public static String resolve(...)

Merge multiple paths to a single absolute path.

Parameters

  • ... One or more relative paths

Returns

Return new absolute path

namespace process

Process handle module, to manage current process resources.

To use it:

var process = require('process');

Summary

Members Descriptions
public static Integer umask(Integer mask) change the current umask,Windows does't support this.
public static Integer umask(String mask) change the current umask,Windows does't support this.
public static Integer umask() return the current umask,Windows does't support this.
public static static exit(Integer code) Exit current process, and return result.
public static String cwd() Return current work path of the operating system.
public static static chdir(String directory) Change the current work path of operating system.
public static Number uptime() returns the system uptime in number of seconds.
public static Object memoryUsage() Get report of memory the current process consumpt.
public static static nextTick(Function func,...) start a fiber
public static SubProcess open(String command,Array args,Object opts) Create chlid process taking charge of stdin and stdout and run bash command.
public static SubProcess open(String command,Object opts) Create chlid process taking charge of stdin and stdout and run bash command.
public static SubProcess start(String command,Array args,Object opts) Create chlid process and run bash command.
public static SubProcess start(String command,Object opts) Create chlid process and run bash command.
public static Integer run(String command,Array args,Object opts) Run bash command and return result code.
public static Integer run(String command,Object opts) Run bash command and return result code.

Members

public static Integer umask(Integer mask)

change the current umask,Windows does't support this.

Parameters

  • mask the mask to set

Returns

the previous mask

public static Integer umask(String mask)

change the current umask,Windows does't support this.

Parameters

  • mask octonary string(e.g: "0664")

Returns

the previous mask

public static Integer umask()

return the current umask,Windows does't support this.

Returns

the current mask

public static static exit(Integer code)

Exit current process, and return result.

Parameters

  • code result of process.

public static String cwd()

Return current work path of the operating system.

Returns

Work path.

public static static chdir(String directory)

Change the current work path of operating system.

Parameters

  • directory The new work path.

public static Number uptime()

returns the system uptime in number of seconds.

Returns

seconds

public static Object memoryUsage()

Get report of memory the current process consumpt.

Returns

Memory report object.

Memory report like this:

{
  "rss": 8622080,
  "heapTotal": 4083456,
  "heapUsed": 1621800
}

among the report:

  • rss Occupation of physical memory.

  • heapTotal Total heap memory of v8.

  • heapUsed Heap memory occupied by v8.

public static static nextTick(Function func,...)

start a fiber

Parameters

  • func function to be executed in the new fiber.

  • ... params which will be passed to the func.

public static SubProcess open(String command,Array args,Object opts)

Create chlid process taking charge of stdin and stdout and run bash command.

Parameters

  • command Bash command to be executed.

  • args Arguments for bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Enviroment variable of child process.
}

Returns

Child process object containing result of command.

public static SubProcess open(String command,Object opts)

Create chlid process taking charge of stdin and stdout and run bash command.

Parameters

  • command Bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Environment variable of child process.
}

Returns

Child process object containing result of command.

public static SubProcess start(String command,Array args,Object opts)

Create chlid process and run bash command.

Parameters

  • command Bash command.

  • args Arguments of bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Environment variable of child process.
}

Returns

Child process object containing result of the command.

public static SubProcess start(String command,Object opts)

Create chlid process and run bash command.

Parameters

  • command Bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Environment variable of child process.
}

Returns

Child process object containing result of the command.

public static Integer run(String command,Array args,Object opts)

Run bash command and return result code.

Parameters

  • command Bash command.

  • args Arguments of bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Environment variable of child process.
}

Returns

Result code of bash command.

public static Integer run(String command,Object opts)

Run bash command and return result code.

Parameters

  • command Bash command.

  • opts Option of child process, such as:

{
    "timeout": 100, // unit ms
    "envs": [] // Environment variable of child process.
}

Returns

Result code of bash command.

namespace profiler

Memory profiler module.

The way to use:

var profiler = require('profiler');

Summary

Members Descriptions
public static static saveSnapshot(String fname) Save a HeapSnapshot with the specified name.
public static HeapSnapshot loadSnapshot(String fname) Load a HeapSnapshot with the specified name.
public static HeapSnapshot takeSnapshot() Get the current HeapSnapshot, HeapSnapshots record the state of the JS heap at some moment.
public static static DeleteAllHeapSnapshots() Delete all HeapSnapshots.

Members

public static static saveSnapshot(String fname)

Save a HeapSnapshot with the specified name.

Parameters

public static HeapSnapshot loadSnapshot(String fname)

Load a HeapSnapshot with the specified name.

Parameters

Returns

Return the HeapSnapshot loaded.

public static HeapSnapshot takeSnapshot()

Get the current HeapSnapshot, HeapSnapshots record the state of the JS heap at some moment.

Returns

Returns the acquired HeapSnapshots.

public static static DeleteAllHeapSnapshots()

Delete all HeapSnapshots.

namespace re

Regexp module.

Summary

Members Descriptions
public static Regex compile(String pattern,String opt) Compile and return a template of regexp.

Members

public static Regex compile(String pattern,String opt)

Compile and return a template of regexp.

Parameters

  • pattern Regexp pattern

  • opt Match type, can be "g", "i" or "gi"

Returns

Return regexp object

namespace rpc

RPC module.

To use it:

var rpc = require('rpc');

Summary

Members Descriptions
public static Handler json(Value hdlr) Generate a json-rpc message converter.

Members

public static Handler json(Value hdlr)

Generate a json-rpc message converter.

Parameters

  • hdlr Built-in handler, handle function or javascript message mapping object, see mq.jsHandler

Returns

Return handler

namespace ssl

ssl/tls module

Summary

Members Descriptions
public static SslSocketnewSocket() Create a SslSocket object, see SslSocket.
public static SslHandlernewHandler() Create a SslHandler object, see SslHandler.
public static SslServernewServer() Create a SslServer object, see SslServer.
public static Stream connect(String url) Create a SslSocket and make connection.
public static static setClientCert(X509Cert crt,PKey key) Set the default client certificate.
public static static loadClientCertFile(String crtFile,String keyFile,String password) Load the default client certificate from a file.

Members

public static SslSocketnewSocket()

Create a SslSocket object, see SslSocket.

public static SslHandlernewHandler()

Create a SslHandler object, see SslHandler.

public static SslServernewServer()

Create a SslServer object, see SslServer.

public static Stream connect(String url)

Create a SslSocket and make connection.

Parameters

  • url Specify URL and protocol, e.g.: ssl://host:port

Returns

Return SslSocket when succeed

public static static setClientCert(X509Cert crt,PKey key)

Set the default client certificate.

Parameters

  • crt 509Cert certificate for client authentication server.

  • key PKey The private key for the client session.

public static static loadClientCertFile(String crtFile,String keyFile,String password)

Load the default client certificate from a file.

Parameters

  • crtFile X509Cert certificate file for client authentication server.

  • keyFile PKey private key file for the client session.

  • password Decryption password

namespace test

Test Suite module that defines the test suite management.

To use it:

var test = require('test');

Summary

Members Descriptions
public static static describe(String name,Function block) The definition of a test module and can be nested definition.
public static static xdescribe(String name,Function block) The definition of a test module to be stopped.
public static static it(String name,Function block) Define a test project.
public static static xit(String name,Function block) Prohibit test project definition.
public static static before(Function func) Define the incident event for current test module.
public static static after(Function func) Define the exit event for current test module.
public static static beforeEach(Function func) Define the incident event for current test project.
public static static afterEach(Function func) Define the exit event for current test project.
public static Integer run(Integer loglevel) Module to start executing definition.
public static Expect expect(Value actual,String msg) expect Grammar test engine
public static static setup(Integer mode) The current test environment initialization script, the test module method to copy a global variable for the current script.

Members

public static static describe(String name,Function block)

The definition of a test module and can be nested definition.

Parameters

  • name Module name

  • block Initial code

public static static xdescribe(String name,Function block)

The definition of a test module to be stopped.

Parameters

  • name Module name

  • block Initial code

public static static it(String name,Function block)

Define a test project.

Parameters

  • name Project name

  • block Test block

public static static xit(String name,Function block)

Prohibit test project definition.

Parameters

  • name Project name

  • block Test block

public static static before(Function func)

Define the incident event for current test module.

Parameters

public static static after(Function func)

Define the exit event for current test module.

Parameters

public static static beforeEach(Function func)

Define the incident event for current test project.

Parameters

public static static afterEach(Function func)

Define the exit event for current test project.

Parameters

public static Integer run(Integer loglevel)

Module to start executing definition.

Parameters

  • loglevel Log output level is specified when tested, ERROR, the project focused on the report the error message is displayed, below ERROR, output information displayed at any time, while higher than ERROR, display only reports

Returns

Return the statistical result of test case, return 0 when meet no error, return the error number of errors.

public static Expect expect(Value actual,String msg)

expect Grammar test engine

Parameters

  • actual Value to test

  • msg Message when error occurs

Returns

Return Expect for chain operations

public static static setup(Integer mode)

The current test environment initialization script, the test module method to copy a global variable for the current script.

Parameters

  • mode Indicates initial mode, default is BDD

namespace util

Common tools module.

Summary

Members Descriptions
public static String format(String fmt,...) Format string with variables.
public static String format(...) Format variables.
public static Boolean isEmpty(Value v) Check if variable is empty(no enumerable property)
public static Boolean isArray(Value v) Check if variable is an array.
public static Boolean isBoolean(Value v) Check if variable is Boolean.
public static Boolean isNull(Value v) Check if variable is Null.
public static Boolean isNullOrUndefined(Value v) Check if variable is Null or Undefined.
public static Boolean isNumber(Value v) Check if variable is a number.
public static Boolean isString(Value v) Check if variable is a string.
public static Boolean isUndefined(Value v) Check if variable is Undefined.
public static Boolean isRegExp(Value v) Check if variable is a regexp object.
public static Boolean isObject(Value v) Check if variable is an object.
public static Boolean isDate(Value v) Check if variable is date object.
public static Boolean isFunction(Value v) Check if variable is a function.
public static Boolean isBuffer(Value v) Check if variable is a Buffer object.
public static Boolean has(Value v,String key) Check if object contains given key.
public static Array keys(Value v) Get an array of all keys.
public static Array values(Value v) Get an array of all values.
public static Value clone(Value v) Clone a variable, copy internal content if it's an object or array.
public static Value extend(Value v,...) Extend one or more values of objects to given object.
public static Object pick(Value v,...) Return a copy of object with filtered attributes.
public static Object omit(Value v,...) Return a copy of object, exclude given attributes.
public static Value first(Value v) Get first element in array.
public static Value first(Value v,Integer n) Get first number of elements in array.
public static Value last(Value v) Get last element in array.
public static Value last(Value v,Integer n) Get number of element in the end of array.
public static Array unique(Value v,Boolean sorted) Get array without duplicates.
public static Array union(...) Union one or more arrays into one unique array.
public static Array intersection(...) Return intersections of arrays.
public static Array flatten(Value arr,Boolean shallow) Convert multi-dimension arrays into one-dimension, only reduce one dimension if you pass shallow argument.
public static Array without(Value arr,...) Return an array without given elements.
public static Array difference(Array list,...) Return differences of arrays.
public static Value each(Value list,Function iterator,Value context) Iterate list in order. If context is passed, then bind iterator to context. Each iteration will pass three arguments to context: element, index and list.
public static Array map(Value list,Function iterator,Value context) Use iterator to map values to new array. If context is passed, then bind iterator to context. Each iteration will pass three arguments to context: element, index and list.
public static Value reduce(Value list,Function iterator,Value memo,Value context) Reduce every element in list to a single number. If context is passed, then bind iterator to context. Each iteration will pass four arguments to context: memo, element, index and list.
public static Object buildInfo() Get current engine and components information.

Members

public static String format(String fmt,...)

Format string with variables.

Parameters

  • fmt Format string

  • ... Aeguments

Returns

Return formatted string

public static String format(...)

Format variables.

Parameters

  • ... Aeguments

Returns

Return formatted string

public static Boolean isEmpty(Value v)

Check if variable is empty(no enumerable property)

Parameters

  • v Variable to check

Returns

Return true when it's empty

public static Boolean isArray(Value v)

Check if variable is an array.

Parameters

  • v Variable to check

Returns

Return true when it's an array

public static Boolean isBoolean(Value v)

Check if variable is Boolean.

Parameters

  • v Variable to check

Returns

Return true when it's a Boolean

public static Boolean isNull(Value v)

Check if variable is Null.

Parameters

  • v Variable to check

Returns

Return true when it's Null

public static Boolean isNullOrUndefined(Value v)

Check if variable is Null or Undefined.

Parameters

  • v Variable to check

Returns

Return true when it's Null or Undefined

public static Boolean isNumber(Value v)

Check if variable is a number.

Parameters

  • v Variable to check

Returns

Return true when it's a number

public static Boolean isString(Value v)

Check if variable is a string.

Parameters

  • v Variable to check

Returns

Return true when it's a string

public static Boolean isUndefined(Value v)

Check if variable is Undefined.

Parameters

  • v Variable to check

Returns

Return true when it's Undefined

public static Boolean isRegExp(Value v)

Check if variable is a regexp object.

Parameters

  • v Variable to check

Returns

Return true when it's a regexp object

public static Boolean isObject(Value v)

Check if variable is an object.

Parameters

  • v Variable to check

Returns

Return true when it's an object

public static Boolean isDate(Value v)

Check if variable is date object.

Parameters

  • v Variable to check

Returns

Return true when it's date object

public static Boolean isFunction(Value v)

Check if variable is a function.

Parameters

  • v Variable to check

Returns

Return true when it's a function

public static Boolean isBuffer(Value v)

Check if variable is a Buffer object.

Parameters

  • v Variable to check

Returns

Return true when it's a Buffer object

public static Boolean has(Value v,String key)

Check if object contains given key.

Parameters

  • v Object to check

  • key Key to query

Returns

Return true when it contains key

public static Array keys(Value v)

Get an array of all keys.

Parameters

  • v Object to check

Returns

Return an array of all keys

public static Array values(Value v)

Get an array of all values.

Parameters

  • v Object to check

Returns

Return an array of all keys

public static Value clone(Value v)

Clone a variable, copy internal content if it's an object or array.

Parameters

  • v Variable to clone

Returns

Return cloned result

public static Value extend(Value v,...)

Extend one or more values of objects to given object.

Parameters

  • v Object to be extended

  • ... One or more objects to extend

Returns

Return extended object

public static Object pick(Value v,...)

Return a copy of object with filtered attributes.

Parameters

  • v Object to filter

  • ... One or more attributes

Returns

Return copy of object

public static Object omit(Value v,...)

Return a copy of object, exclude given attributes.

Parameters

  • v Object to filter

  • ... One or more attributes to exclude

Returns

Return copy of object

public static Value first(Value v)

Get first element in array.

Parameters

  • v Array to access

Returns

Return element

public static Value first(Value v,Integer n)

Get first number of elements in array.

Parameters

  • v Array to access

  • n Number of elements to get

Returns

Return array of elements

public static Value last(Value v)

Get last element in array.

Parameters

  • v Array to access

Returns

Return element

public static Value last(Value v,Integer n)

Get number of element in the end of array.

Parameters

  • v Array to access

  • n Number of elements to get

Returns

Return array of elements

public static Array unique(Value v,Boolean sorted)

Get array without duplicates.

Parameters

  • v Array to access

  • sorted Indicates whether to sort or not, will use quick sort

Returns

Return unique array

public static Array union(...)

Union one or more arrays into one unique array.

Parameters

  • ... Arrays to union

Returns

Return unioned array

public static Array intersection(...)

Return intersections of arrays.

Parameters

  • ... Arrays to check

Returns

Return intersections

public static Array flatten(Value arr,Boolean shallow)

Convert multi-dimension arrays into one-dimension, only reduce one dimension if you pass shallow argument.

Parameters

  • arr Array to convert

  • shallow Indicates whether to reduce only one dimension or not, default is false

Returns

Return converted array

public static Array without(Value arr,...)

Return an array without given elements.

Parameters

  • arr Array to access

  • ... Elements to exclude

Returns

Return result array

public static Array difference(Array list,...)

Return differences of arrays.

Parameters

  • list Arrays to check

Returns

Return differences

public static Value each(Value list,Function iterator,Value context)

Iterate list in order. If context is passed, then bind iterator to context. Each iteration will pass three arguments to context: element, index and list.

Parameters

  • list List or object to iterate

  • iterator Iterator callback

  • context Context object for binding

Returns

Return list itself

public static Array map(Value list,Function iterator,Value context)

Use iterator to map values to new array. If context is passed, then bind iterator to context. Each iteration will pass three arguments to context: element, index and list.

Parameters

  • list List or object to iterate

  • iterator Iterator callback

  • context Context object for binding

Returns

Return result array

public static Value reduce(Value list,Function iterator,Value memo,Value context)

Reduce every element in list to a single number. If context is passed, then bind iterator to context. Each iteration will pass four arguments to context: memo, element, index and list.

Parameters

  • list List or object to iterate

  • iterator Iterator callback

  • memo Initial value

  • context Context object for binding

Returns

Return result array

public static Object buildInfo()

Get current engine and components information.

Returns

Struct info:

{
  "fibjs": "0.1.0",
  "svn": 1753,
  "build": "Dec 10 2013 21:44:17",
  "vender": {
    "ev": "4.11",
    "exif": "0.6.21",
    "gd": "2.1.0-alpha",
    "jpeg": "8.3",
    "log4cpp": "1.0",
    "mongo": "0.7",
    "pcre": "8.21",
    "png": "1.5.4",
    "sqlite": "3.8.1",
    "tiff": "3.9.5",
    "uuid": "1.6.2",
    "v8": "3.23.17 (candidate)",
    "zlib": "1.2.7",
    "zmq": "3.1"
  }
}

namespace uuid

uuid unique id module

Fundamental module, used for create uuid

var uuid = require('uuid');

Summary

Members Descriptions
public static uuidValue uuid(String s) Generate uuid by given string.
public static uuidValue uuid(Buffer data) Generate uuid by given binary data.
public static uuidValue node() Generate uuid by time and host name.
public static uuidValue md5(Integer ns,String name) Generate uuid by given md5.
public static uuidValue random() Generate uuid randomly.
public static uuidValue sha1(Integer ns,String name) Generate uuid by given sha1.

Members

public static uuidValue uuid(String s)

Generate uuid by given string.

Parameters

  • s String to describe uuid

Returns

Return uuidValue object

public static uuidValue uuid(Buffer data)

Generate uuid by given binary data.

Parameters

  • data Data to describe uuid

Returns

Return uuidValue object

public static uuidValue node()

Generate uuid by time and host name.

Returns

Return uuidValue object

public static uuidValue md5(Integer ns,String name)

Generate uuid by given md5.

Parameters

Returns

Return uuidValue object

public static uuidValue random()

Generate uuid randomly.

Returns

Return uuidValue object

public static uuidValue sha1(Integer ns,String name)

Generate uuid by given sha1.

Parameters

Returns

Return uuidValue object

namespace vm

Safe SandBox module, to isolate runtime based on safety level.

By establishing a safe SandBox, you can limit the accessible resources when the script runs, and isolate different script execution environment, also can be customized for different environments base module to ensure the safety of the overall operating environment.

Following example demonstrates a sandbox which is only allowed for accessing assert module, and add a and b as customized modules.

var vm = require('vm');
var sbox = new vm.SandBox({
  a: 100,
  b: 200,
  assert: require('assert')
});

var mod_in_sbox = sbox.require('./path/to/mod');

Summary

Members Descriptions
public static SandBoxnewSandBox() Create a SandBox object, see SandBox.

Members

public static SandBoxnewSandBox()

Create a SandBox object, see SandBox.

namespace websocket

websocket support module

To use it:

var websocket = require('websocket');

Summary

Members Descriptions
public static WebSocketMessagenewMessage() Create one websocket message object, refer WebSocketMessage.
public static WebSocketHandlernewHandler() Create one websocket packet protocol conversion processor, refer WebSocketHandler.
public static Stream connect(String url) Create one websocket connection, and return a completed connection Stream object.

Members

public static WebSocketMessagenewMessage()

Create one websocket message object, refer WebSocketMessage.

public static WebSocketHandlernewHandler()

Create one websocket packet protocol conversion processor, refer WebSocketHandler.

public static Stream connect(String url)

Create one websocket connection, and return a completed connection Stream object.

Parameters

  • url Specifies the connection url,support ws:// and wss:// protocol

Returns

Return a completed connection Stream object, which can be Socket or SslSocket

namespace xml

xml module

Summary

Members Descriptions
public static XmlDocumentnewDocument() xml document object, see XmlDocument object
public static XmlDocument parse(String source,String type) Parse xml/html text and create XmlDocument object, does not support multiple languages.
public static XmlDocument parse(Buffer source,String type) Parse xml/html and create XmlDocument object, convert by given language.
public static String serialize(XmlNode node) Serialize XmlNode to string.

Members

public static XmlDocumentnewDocument()

xml document object, see XmlDocument object

public static XmlDocument parse(String source,String type)

Parse xml/html text and create XmlDocument object, does not support multiple languages.

Parameters

  • source xml/html text to parse

  • type Indicates text type, default is text/xml, and can be text/html as well

Returns

Return created XmlDocument object

public static XmlDocument parse(Buffer source,String type)

Parse xml/html and create XmlDocument object, convert by given language.

Parameters

  • source xml/html text to parse

  • type Indicates text type, default is text/xml, and can be text/html as well

Returns

Return created XmlDocument object

public static String serialize(XmlNode node)

Serialize XmlNode to string.

Parameters

Returns

Return serialized string

namespace zip

Zip file processing module.

It can be used to compress and decompress file into or from zip file. The way to use:

var zip = require('zip');

Summary

Members Descriptions
public static Boolean isZipFile(String filename) Judge if the file is zip file.
public static ZipFile open(String path,String mod,Integer compress_type) Open a zip file.
public static ZipFile open(Buffer data,String mod,Integer compress_type) Open buffer of zip file data.
public static ZipFile open(SeekableStream strm,String mod,Integer compress_type) Open stream of zip file data.

Members

public static Boolean isZipFile(String filename)

Judge if the file is zip file.

Parameters

  • filename to be judged.

Returns

Judge result, true means yes.

public static ZipFile open(String path,String mod,Integer compress_type)

Open a zip file.

Parameters

  • path The path of file to be opened.

  • mod File open mode, "r" means read only, "w" means create and overwrite if the file exists, "a" means append after the zip file.

  • compress_type Compress type, ZIP_STORED means no compress and for storage only. The default parameter is ZIP_DEFLATED, it depends on library zlib in compressing.

Returns

The zip file object.

public static ZipFile open(Buffer data,String mod,Integer compress_type)

Open buffer of zip file data.

Parameters

  • data Buffer of zip file data.

  • mod File open mode, "r" means read only, "w" means create and overwrite if the file exists, "a" means append after the zip file.

  • compress_type Compress type, ZIP_STORED means no compress and for storage only. The default parameter is ZIP_DEFLATED, it depends on library zlib in compressing.

Returns

The zip file object.

public static ZipFile open(SeekableStream strm,String mod,Integer compress_type)

Open stream of zip file data.

Parameters

  • strm Stream of zip file data.

  • mod File open mode, "r" means read only, "w" means create and overwrite if the file exists, "a" means append after the zip file.

  • compress_type Compress type, ZIP_STORED means no compress and for storage only. The default parameter is ZIP_DEFLATED, it depends on library zlib in compressing.

Returns

The zip file object.

namespace zlib

zlib compression and decompression module

To use it:

var zlib = require('zlib');

Summary

Members Descriptions
public static Buffer deflate(Buffer data,Integer level) Use deflate to compress data (zlib format)
public static static deflateTo(Buffer data,Stream stm,Integer level) Use deflate to compress data to stream (zlib format)
public static static deflateTo(Stream src,Stream stm,Integer level) Use deflate to compress a stream data to another (zlib format)
public static Buffer inflate(Buffer data) Use deflate to decompress data (zlib format)
public static static inflateTo(Buffer data,Stream stm) Use deflate to decompress data to stream (zlib format)
public static static inflateTo(Stream src,Stream stm) Use deflate to decompress a stream data to another (zlib format)
public static Buffer gzip(Buffer data) Use gzip to compress data.
public static static gzipTo(Buffer data,Stream stm) Use gzip to compress data to stream.
public static static gzipTo(Stream src,Stream stm) Use gzip to compress a stream data to another.
public static Buffer gunzip(Buffer data) Use gzip to decompress data.
public static static gunzipTo(Buffer data,Stream stm) Use gzip to decompress data to stream.
public static static gunzipTo(Stream src,Stream stm) Use gzip to decompress a stream data to another.
public static Buffer deflateRaw(Buffer data,Integer level) Use deflate to compress data (deflateRaw)
public static static deflateRawTo(Buffer data,Stream stm,Integer level) Use deflate to compress data to stream (deflateRaw)
public static static deflateRawTo(Stream src,Stream stm,Integer level) Use deflate to compress a stream data to another (deflateRaw)
public static Buffer inflateRaw(Buffer data) Use deflate to decompress data (deflateRaw)
public static static inflateRawTo(Buffer data,Stream stm) Use deflate to decompress data to stream (deflateRaw)
public static static inflateRawTo(Stream src,Stream stm) Use deflate to decompress a stream data to another (deflateRaw)

Members

public static Buffer deflate(Buffer data,Integer level)

Use deflate to compress data (zlib format)

Parameters

  • data Raw data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

Returns

Return compressed binary

public static static deflateTo(Buffer data,Stream stm,Integer level)

Use deflate to compress data to stream (zlib format)

Parameters

  • data Raw data

  • stm Stream to write compressed data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

public static static deflateTo(Stream src,Stream stm,Integer level)

Use deflate to compress a stream data to another (zlib format)

Parameters

  • src Original stream

  • stm Target stream to write compressed data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

public static Buffer inflate(Buffer data)

Use deflate to decompress data (zlib format)

Parameters

  • data Compressed data

Returns

Return decompressed binary

public static static inflateTo(Buffer data,Stream stm)

Use deflate to decompress data to stream (zlib format)

Parameters

  • data Compressed data

  • stm Stream to write decompressed data

public static static inflateTo(Stream src,Stream stm)

Use deflate to decompress a stream data to another (zlib format)

Parameters

  • src Original stream

  • stm Target stream to write decompressed data

public static Buffer gzip(Buffer data)

Use gzip to compress data.

Parameters

  • data Raw data

Returns

Return compressed binary

public static static gzipTo(Buffer data,Stream stm)

Use gzip to compress data to stream.

Parameters

  • data Raw data

  • stm Stream to write compressed data

public static static gzipTo(Stream src,Stream stm)

Use gzip to compress a stream data to another.

Parameters

  • src Original stream

  • stm Target stream to write compressed data

public static Buffer gunzip(Buffer data)

Use gzip to decompress data.

Parameters

  • data Compressed data

Returns

Return decompressed binary

public static static gunzipTo(Buffer data,Stream stm)

Use gzip to decompress data to stream.

Parameters

  • data Compressed data

  • stm Stream to write decompressed data

public static static gunzipTo(Stream src,Stream stm)

Use gzip to decompress a stream data to another.

Parameters

  • src Original stream

  • stm Target stream to write decompressed data

public static Buffer deflateRaw(Buffer data,Integer level)

Use deflate to compress data (deflateRaw)

Parameters

  • data Raw data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

Returns

Return compressed binary

public static static deflateRawTo(Buffer data,Stream stm,Integer level)

Use deflate to compress data to stream (deflateRaw)

Parameters

  • data Raw data

  • stm Stream to write compressed data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

public static static deflateRawTo(Stream src,Stream stm,Integer level)

Use deflate to compress a stream data to another (deflateRaw)

Parameters

  • src Original stream

  • stm Target stream to write compressed data

  • level Indicate compression level, default is DEFAULT_COMPRESSION

public static Buffer inflateRaw(Buffer data)

Use deflate to decompress data (deflateRaw)

Parameters

  • data Compressed data

Returns

Return decompressed binary

public static static inflateRawTo(Buffer data,Stream stm)

Use deflate to decompress data to stream (deflateRaw)

Parameters

  • data Compressed data

  • stm Stream to write decompressed data

public static static inflateRawTo(Stream src,Stream stm)

Use deflate to decompress a stream data to another (deflateRaw)

Parameters

  • src Original stream

  • stm Target stream to write decompressed data

class AsyncWait

class AsyncWait
  : public Handler

MessageHandler object for asynchronous waiting.

Summary

Members Descriptions
public end() Finish waiting, moving on to handle the message.
public Handler invoke(object v) handle a message or an object
public dispose() Force dispose object immediately.
public String toString() Return string representation of object, normally is "[Native Object]" and can be implemented by object itself.
public Value toJSON(String key) Return JSON representation of object, normally is readable attributes collection.
public Value valueOf() Return JSON representation of object.

Members

public end()

Finish waiting, moving on to handle the message.

handle a message or an object

Parameters

  • v specify the message or object to be handled

Returns

return the handler of the next step

public dispose()

Force dispose object immediately.

public String toString()

Return string representation of object, normally is "[Native Object]" and can be implemented by object itself.

Returns

Return string representation

public Value toJSON(String key)

Return JSON representation of object, normally is readable attributes collection.

Parameters

  • key Not used

Returns

Return JSON representation

public Value valueOf()

Return JSON representation of object.

Returns

Return JSON representation of object

class Buffer

class Buffer
  : public object

Binary buffer used in dealing with I/O reading and writing.

Buffer object is a global basic class which can be created by "new Buffer(...)" at anytime:

var buf = new Buffer();

Summary

Members Descriptions
public Integer operator[] The binary data in the buffer can be accessed by using subscript.
public readonly Integer length The buffer size.
public Buffer(Array datas) Buffer constructor.
public Buffer(Buffer buffer) Buffer constructor.
public Buffer(String str,String codec) Buffer constructor.
public Buffer(Integer size) Buffer constructor.
public resize(Integer sz) Resize the buffer.
public append(Array datas) Write an array into the buffer.
public append(Buffer data) Write a set of binary data into the buffer.
public append(String str,String codec) Write a string encoded in utf-8 into buffer.
public Integer write(String str,Integer offset,Integer length,String codec) Writes string to the buffer at offset using the given encoding.
public fill(Integer v,Integer offset,Integer end) Fill the buffer with the specified objects.
public fill(Buffer v,Integer offset,Integer end) Fill the buffer with the specified objects.
public fill(String v,Integer offset,Integer end) Fill the buffer with the specified objects.
public Boolean equals(Buffer buf) Whether this and otherBuffer have the same bytes.
public Integer compare(Buffer buf) Compare the contents of the buffer.
public Integer copy(Buffer targetBuffer,Integer targetStart,Integer sourceStart,Integer sourceEnd) Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined the targetStart and sourceStart parameters default to 0 while sourceEnd defaults to buffer.length.
public Integer readUInt8(Integer offset,Boolean noAssert) Read an unsigned 8-bit integer from the buffer.
public Integer readUInt16LE(Integer offset,Boolean noAssert) Read an unsigned 16-bit integer from the buffer and use the little-endian format for storage.
public Integer readUInt16BE(Integer offset,Boolean noAssert) Read an unsigned 16-bit integer from the buffer and use the big-endian format for storage.
public Long readUInt32LE(Integer offset,Boolean noAssert) Read an unsigned 32-bit integer from the buffer and use the little-endian format for storage.
public Long readUInt32BE(Integer offset,Boolean noAssert) Read an unsigned 32-bit integer from the buffer and use the big-endian format for storage.
public Integer readInt8(Integer offset,Boolean noAssert) Read an 8-bit integer from the buffer.
public Integer readInt16LE(Integer offset,Boolean noAssert) Read an 16-bit integer from the buffer and use the little-endian format for storage.
public Integer readInt16BE(Integer offset,Boolean noAssert) Read an 16-bit integer from the buffer and use the big-endian format for storage.
public Integer readInt32LE(Integer offset,Boolean noAssert) Read an 32-bit integer from the buffer and use the little-endian format for storage.
public Integer readInt32BE(Integer offset,Boolean noAssert) Read an 32-bit integer from the buffer and use the big-endian format for storage.
public Int64 readInt64LE(Integer offset,Boolean noAssert) Read an 64-bit integer from the buffer and use the little-endian format for storage.
public Int64 readInt64BE(Integer offset,Boolean noAssert) Read an 64-bit integer from the buffer and use the big-endian format for storage.
public Number readFloatLE(Integer offset,Boolean noAssert) Read a float from the buffer and use the little-endian format for storage.
public Number readFloatBE(Integer offset,Boolean noAssert) Read a float from the buffer and use the big-endian format for storage.
public Number readDoubleLE(Integer offset,Boolean noAssert) Read a double from the buffer and use the little-endian format for storage.
public Number readDoubleBE(Integer offset,Boolean noAssert) Read a double from the buffer and use the big-endian format for storage.
public writeUInt8(Integer value,Integer offset,Boolean noAssert) Write an unsigned 8-bit integer into the buffer.
public writeUInt16LE(Integer value,Integer offset,Boolean noAssert) Write an unsigned 16-bit integer into the buffer and use the little-endian format for storage.
public writeUInt16BE(Integer value,Integer offset,Boolean noAssert) Write an unsigned 16-bit integer into the buffer and use the big-endian format for storage.
public writeUInt32LE(Long value,Integer offset,Boolean noAssert) Write an unsigned 32-bit integer into the buffer and use the little-endian format for storage.
public writeUInt32BE(Long value,Integer offset,Boolean noAssert) Write an unsigned 32-bit integer into the buffer and use the big-endian format for storage.
public writeInt8(Integer value,Integer offset,Boolean noAssert) Write an 8-bit integer into the buffer.
public writeInt16LE(Integer value,Integer offset,Boolean noAssert) Write a 16-bit integer into the buffer and use the little-endian format for storage.
public writeInt16BE(Integer value,Integer offset,Boolean noAssert) Write a 16-bit integer into the buffer and use the big-endian format for storage.
public writeInt32LE(Integer value,Integer offset,Boolean noAssert) Write a 32-bit integer into the buffer and use the little-endian format for storage.
public writeInt32BE(Integer value,Integer offset,Boolean noAssert) Write a 32-bit integer into the buffer and use the big-endian format for storage.
public writeInt64LE(Int64 value,Integer offset,Boolean noAssert) Write a 64-bit integer into the buffer and use the little-endian format for storage.
public writeInt64BE(Int64 value,Integer offset,Boolean noAssert) Write a 64-bit integer into the buffer and use the big-endian format for storage.
public writeFloatLE(Number value,Integer offset,Boolean noAssert) Write a float into the buffer and use the little-endian format for storage.
public writeFloatBE(Number value,Integer offset,Boolean noAssert) Write a float into the buffer and use the big-endian format for storage.
public writeDoubleLE(Number value,Integer offset,Boolean noAssert) Write a double into the buffer and use the little-endian format for storage.
public writeDoubleBE(Number value,Integer offset,Boolean noAssert) Write a double into the buffer and use the big-endian format for storage.
public Buffer slice(Integer start,Integer end) return a new buffer that contains data in the specified range. If the data is out of range of the buffer, return the available part of the data.
public String hex() Store the data in the buffer with hexadecimal encoding?
public String base64() Store the data in the buffer with base64 encoding?
public String toString(String codec,Integer offset,Integer end) return the encoded string of the binary data
public String toString() return the utf8-encoded string of the binary data
public dispose() Force dispose object immediately.
public Value toJSON(String key) Return JSON representation of object, normally is readable attributes collection.
public Value valueOf() Return JSON representation of object.

Members

public Integer operator[]

The binary data in the buffer can be accessed by using subscript.

public readonly Integer length

The buffer size.

public Buffer(Array datas)

Buffer constructor.

Parameters

  • datas Initial data array

public Buffer(Buffer buffer)

Buffer constructor.

Parameters

  • buffer otherBuffer

public Buffer(String str,String codec)

Buffer constructor.

Parameters

  • str Initial string encoded in UTF-8, by default it will create an empty object.

  • codec The encode format, can be "hex", “base64”, "utf8" or any other character sets supported by the system.

public Buffer(Integer size)

Buffer constructor.

Parameters

  • size Initial cache size

public resize(Integer sz)

Resize the buffer.

Parameters

  • sz New size

public append(Array datas)

Write an array into the buffer.

Parameters

  • datas Initial data array

public append(Buffer data)

Write a set of binary data into the buffer.

Parameters

  • data Initial binary data

public append(String str,String codec)

Write a string encoded in utf-8 into buffer.

Parameters

  • str String to write

  • codec Coded format, can be "hex", “base64”, "utf8" or any other character sets supported by the system.

public Integer write(String str,Integer offset,Integer length,String codec)

Writes string to the buffer at offset using the given encoding.

Parameters

  • str String - data to be written to buffer

  • offset Number, Optional, Default 0

  • length Number, Optional, Default -1

  • codec Coded format, can be "hex", “base64”, "utf8" or any other character sets supported

Returns

Returns number of octets written.

public fill(Integer v,Integer offset,Integer end)

Fill the buffer with the specified objects.

Parameters

  • v Data intend to be filled, and will fill the entire buffer when the offset and end is not specified.

  • offset Number, Optional, Default 0

  • end Number, Optional, Default -1

public fill(Buffer v,Integer offset,Integer end)

Fill the buffer with the specified objects.

Parameters

  • v Data intend to be filled, and will fill the entire buffer when the offset and end is not specified.

  • offset Number, Optional, Default 0

  • end Number, Optional, Default -1

public fill(String v,Integer offset,Integer end)

Fill the buffer with the specified objects.

Parameters

  • v Data intend to be filled, and will fill the entire buffer when the offset and end is not specified.

  • offset Number, Optional, Default 0

  • end Number, Optional, Default -1

public Boolean equals(Buffer buf)

Whether this and otherBuffer have the same bytes.

Parameters

  • buf otherBuffer

Returns

Returns a boolean of whether this and otherBuffer have the same bytes.

public Integer compare(Buffer buf)

Compare the contents of the buffer.

Parameters

  • buf otherBuffer

Returns

Returns a number indicating whether this comes before or after or is the same as the otherBuffer in sort order.

public Integer copy(Buffer targetBuffer,Integer targetStart,Integer sourceStart,Integer sourceEnd)

Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined the targetStart and sourceStart parameters default to 0 while sourceEnd defaults to buffer.length.

Parameters

  • targetBuffer Buffer object - Buffer to copy into

  • targetStart Number, Optional, Default: 0

  • sourceStart Number, Optional, Default: 0

  • sourceEnd Number, Optional, Default: -1, represent buffer.length

Returns

Copied data byte length

public Integer readUInt8(Integer offset,Boolean noAssert)

Read an unsigned 8-bit integer from the buffer.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readUInt16LE(Integer offset,Boolean noAssert)

Read an unsigned 16-bit integer from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readUInt16BE(Integer offset,Boolean noAssert)

Read an unsigned 16-bit integer from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Long readUInt32LE(Integer offset,Boolean noAssert)

Read an unsigned 32-bit integer from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Long readUInt32BE(Integer offset,Boolean noAssert)

Read an unsigned 32-bit integer from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readInt8(Integer offset,Boolean noAssert)

Read an 8-bit integer from the buffer.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readInt16LE(Integer offset,Boolean noAssert)

Read an 16-bit integer from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readInt16BE(Integer offset,Boolean noAssert)

Read an 16-bit integer from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readInt32LE(Integer offset,Boolean noAssert)

Read an 32-bit integer from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Integer readInt32BE(Integer offset,Boolean noAssert)

Read an 32-bit integer from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Int64 readInt64LE(Integer offset,Boolean noAssert)

Read an 64-bit integer from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Int64 readInt64BE(Integer offset,Boolean noAssert)

Read an 64-bit integer from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted integer

public Number readFloatLE(Integer offset,Boolean noAssert)

Read a float from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted float

public Number readFloatBE(Integer offset,Boolean noAssert)

Read a float from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted float

public Number readDoubleLE(Integer offset,Boolean noAssert)

Read a double from the buffer and use the little-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted double

public Number readDoubleBE(Integer offset,Boolean noAssert)

Read a double from the buffer and use the big-endian format for storage.

Parameters

  • offset The beginning of the address to read

  • noAssert If true, then do not throw an error when overread. By default it's false.

Returns

The targeted double

public writeUInt8(Integer value,Integer offset,Boolean noAssert)

Write an unsigned 8-bit integer into the buffer.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeUInt16LE(Integer value,Integer offset,Boolean noAssert)

Write an unsigned 16-bit integer into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeUInt16BE(Integer value,Integer offset,Boolean noAssert)

Write an unsigned 16-bit integer into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeUInt32LE(Long value,Integer offset,Boolean noAssert)

Write an unsigned 32-bit integer into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeUInt32BE(Long value,Integer offset,Boolean noAssert)

Write an unsigned 32-bit integer into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt8(Integer value,Integer offset,Boolean noAssert)

Write an 8-bit integer into the buffer.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt16LE(Integer value,Integer offset,Boolean noAssert)

Write a 16-bit integer into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt16BE(Integer value,Integer offset,Boolean noAssert)

Write a 16-bit integer into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt32LE(Integer value,Integer offset,Boolean noAssert)

Write a 32-bit integer into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt32BE(Integer value,Integer offset,Boolean noAssert)

Write a 32-bit integer into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt64LE(Int64 value,Integer offset,Boolean noAssert)

Write a 64-bit integer into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeInt64BE(Int64 value,Integer offset,Boolean noAssert)

Write a 64-bit integer into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeFloatLE(Number value,Integer offset,Boolean noAssert)

Write a float into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeFloatBE(Number value,Integer offset,Boolean noAssert)

Write a float into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeDoubleLE(Number value,Integer offset,Boolean noAssert)

Write a double into the buffer and use the little-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public writeDoubleBE(Number value,Integer offset,Boolean noAssert)

Write a double into the buffer and use the big-endian format for storage.

Parameters

  • value The value to write

  • offset The beginning of the address to write

  • noAssert If true, then do not throw an error when overwrite. By default it's false.

public Buffer slice(Integer start,Integer end)

return a new buffer that contains data in the specified range. If the data is out of range of the buffer, return the available part of the data.

Parameters

  • start The start of the specified range, by default it's the beginning of the buffer

  • end The end of the specified range, by default it's the end of the buffer

public String hex()

Store the data in the buffer with hexadecimal encoding?

Returns

The encoded string

public String base64()

Store the data in the buffer with base64 encoding?

Returns

The encoded string

public String toString(String codec,Integer offset,Integer end)

return the encoded string of the binary data

Parameters

  • codec The encode format, can be "hex", “base64”, "utf8" or any other character sets supported by the system.

  • offset The start position of string, Default: 0

  • end The end position of string, Default: -1

Returns

The string representing the value of the buffer.

public String toString()

return the utf8-encoded string of the binary data

Returns

The string representing the value of the buffer.

public dispose()

Force dispose object immediately.

public Value toJSON(String key)

Return JSON representation of object, normally is readable attributes collection.

Parameters

  • key Not used

Returns

Return JSON representation

public Value valueOf()

Return JSON representation of object.

Returns

Return JSON representation of object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment