Skip to main content

Using Built-in JS Libraries

tip

EchoAPI comes with a wide range of practical third-party JavaScript libraries that you can easily use in pre-request and post-request scripts, enhancing your development process.

List of Built-in Libraries

Note

No need to reference built-in libraries using require/import; you can use them directly!

_

lodash - A utility library for JavaScript

Usage Documentation Example:

_.forEach([1, 2], function(value) {
console.log(value);
});
// => Logs 1 then 2.

_.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).

uuid

Generate UUID

Usage Documentation

let uuidStr = uuid.v4();
console.log(uuidStr) // e.g., 78fdb729-ed5f-4dff-860c-d87d02b43078

CryptoJS

A library for encoding/decoding with methods like Base64, MD5, SHA, AES, etc.
Example Usage:

Usage Documentation
(Documentation backup link)

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString();

// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText); // 'my message'

JSON5

Provides more flexible parsing and stringifying JSON data

Usage Documentation
(Documentation backup link)

let _json = {
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom! \\\nNo \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: ['arrays',],
"backwardsCompatible": "with JSON",
};
console.log(JSON5.stringify(_json))

let _jsonStr = {
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom! \\\nNo \\\\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: ['arrays',],
"backwardsCompatible": "with JSON",
};
console.log(JSON5.parse(_jsonStr))

jsonpath

Query and manipulate JavaScript objects with JSONPath

Usage Documentation

var cities = [
{ name: "London", "population": 8615246 },
{ name: "Berlin", "population": 3517424 },
{ name: "Madrid", "population": 3165235 },
{ name: "Rome", "population": 2870528 }
];

var names = jsonpath.query(cities, '$..name');
console.log(names)
// [ "London", "Berlin", "Madrid", "Rome" ]

x2js

Convert between XML and JavaScript objects

Usage Documentation

xml2Json()

XML to JSON method, example:

let xml =
Tove
Jani
Reminder
Don't forget me this weekend!;

let json = xml2Json(xml);
console.log(json);

// Returns
// {
// "note": {
// "to": "Tove",
// "from": "Jani",
// "heading": "Reminder",
// "body": "Don't forget me this weekend!"
// }
// }

chai

A BDD / TDD assertion library

Usage Documentation

moment

A date processing library (without locales)

Usage Documentation

dayjs

A lightweight JavaScript library for working with time and dates

Usage Documentation

JSEncrypt

A JavaScript library for executing OpenSSL RSA encryption, decryption, and key generation.

Usage Documentation
(Documentation backup link)

//rsa encryption
var encryptor = new JSEncrypt() // Create an encryption object instance
//The public key generated by SSL before, be careful not to have spaces when copying
var pubKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1QQRl0HlrVv6kGqhgonD6A9SU6ZJpnEN+Q0blT/ue6Ndt97WRfxtSAs0QoquTreaDtfC4RRX4o+CU6BTuHLUm+eSvxZS9TzbwoYZq7ObbQAZAY+SYDgAA5PHf1wNN20dGMFFgVS/y0ZWvv1UNa2laEz0I8Vmr5ZlzIn88GkmSiQIDAQAB-----END PUBLIC KEY-----'
encryptor.setPublicKey(pubKey)//Set public key
var rsaPassWord = encryptor.encrypt('The content to be encrypted') // Encrypt the content
//rsa decryption
var decrypt = new JSEncrypt()// Create a decryption object instance
//The private key generated by SSL before
var priKey = '-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQC1QQRl0HlrVv6kGqhgonD6A9SU6ZJpnEN+Q0blT/ue6Ndt97WRfxtSAs0QoquTreaDtfC4RRX4o+CU6BTuHLUm+eSvxZS9TzbwoYZq7ObbQAZAY+SYDgAA5PHf1wNN20dGMFFgVS/y0ZWvv1UNa2laEz0I8Vmr5ZlzIn88GkmSiQIDAQABAoGBAKYDKP4AFlXkVlMEP5hS8FtuSrUhwgKNJ5xsDnFV8sc3yKlmKp1a6DETc7N66t/Wdb3JVPPSAy+7GaYJc7IsBRZgVqhrjiYiTO3ZvJv3nwAT5snCoZrDqlFzNhR8zvUiyAfGD1pExBKLZKNH826dpfoKD2fYlBVOjz6i6dTKBvCJAkEA/GtL6q1JgGhGLOUenFveqOHJKUydBAk/3jLZksQqIaVxoB+jRQNOZjeSO9er0fxgI2kh0NnfXEvH+v326WxjBwJBALfTRar040v71GJq1m8eFxADIiPDNh5JD2yb71FtYzH9J5/d8SUHI/CUFoROOhxr3DpagmrnTn28H0088vubKe8CQDKMOhOwx/tS5lqvN0YQj7I6JNKEaR0ZzRRuEmv1pIpAW1S5gTScyOJnVn1tXxcZ9xagQwlT2ArfkhiNKxjrf5kCQAwBSDN5+r4jnCMxRv/Kv0bUbY5YWVhw/QjixiZTNn81QTk3jWAVr0su4KmTUkg44xEMiCfjI0Ui3Ah3SocUAxECQAmHCjy8WPjhJN8y0MXSX05OyPTtysrdFzm1pwZNm/tWnhW7GvYQpvE/iAcNrNNb5k17fCImJLH5gbdvJJmCWRk=-----END RSA PRIVATE KEY----'
decrypt.setPrivateKey(priKey)//Set up the key.
var uncrypted = decrypt.decrypt(encrypted)//Decrypt the content encrypted with the public key before decryption.

sm-crypto

JavaScript version. Support encryption and decryption of sm2, sm3, sm4.

sm2

Get the key pair

let keypair = sm2.generateKeyPairHex()

publicKey = keypair.publicKey // Public Key
privateKey = keypair.privateKey // Private Key

// Generating a public key with 130 bits is too long, compressing it down to 66 bits is possible.

const compressedPublicKey = sm2.compressPublicKeyHex(publicKey) // compressedPublicKey is equivalent to publicKey.
sm2.comparePublicKeyHex(publicKey, compressedPublicKey) //Determining the equivalence of public keys.

// Custom random number, the parameters will be directly passed to the BigInteger constructor of the jsbn library.
// Note: Developers using custom random numbers need to ensure that the random numbers provided meet cryptographic security standards.

let keypair2 = sm2.generateKeyPairHex('123123123123123')
let keypair3 = sm2.generateKeyPairHex(256, SecureRandom)

let verifyResult = sm2.verifyPublicKey(publicKey) // Validate Public Key
verifyResult = sm2.verifyPublicKey(compressedPublicKey) // Validate Public Key

Encrypt Decrypt

const cipherMode = 1 // 1 - C1C3C2,0 - C1C2C3,default is 1.

let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode) // Encryption result
let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode) // Decryption result

encryptData = sm2.doEncrypt(msgArray, publicKey, cipherMode) // Encryption result, input array
decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode, {output: 'array'}) // Decryption result, output array

Signature Verification

ps:In theory, doing pure signatures only is the fastest.


// Pure signature + generating elliptic curve points
let sigValueHex = sm2.doSignature(msg, privateKey) // Signature
let verifyResult = sm2.doVerifySignature(msg, sigValueHex, publicKey) // Verification Result

// Pure signature
let sigValueHex2 = sm2.doSignature(msg, privateKey, {
pointPool: [sm2.getPoint(), sm2.getPoint(), sm2.getPoint(), sm2.getPoint()], // Passing in pre-generated elliptic curve points can speed up the signing process.
}) // Signature
let verifyResult2 = sm2.doVerifySignature(msg, sigValueHex2, publicKey) // Verification Result

// Pure signature + generation of elliptic curve points + DER encoding/decoding
let sigValueHex3 = sm2.doSignature(msg, privateKey, {
der: true,
}) // Signature
let verifyResult3 = sm2.doVerifySignature(msg, sigValueHex3, publicKey, {
der: true,
}) // Verification Result

// Pure signature + Generate elliptic curve points + SM3 hashing
let sigValueHex4 = sm2.doSignature(msg, privateKey, {
hash: true,
}) // Signature
let verifyResult4 = sm2.doVerifySignature(msg, sigValueHex4, publicKey, {
hash: true,
}) // Verification Result

// Pure Signature + Generate Elliptic Curve Points + SM3 Hashing (without public key derivation)
let sigValueHex5 = sm2.doSignature(msg, privateKey, {
hash: true,
publicKey, // If the public key is passed in, the process of deriving the public key in SM3 hashing can be omitted, which makes it faster than just a pure signature combined with generating elliptic curve points and SM3 hashing.

})
let verifyResult5 = sm2.doVerifySignature(msg, sigValueHex5, publicKey, {
hash: true,
publicKey,
})

// Pure Signature + Generate Elliptic Curve Points + SM3 Hashing + No Public Key Derivation + Add User ID (length less than 8192)
// The default User ID value is 1234567812345678.
let sigValueHex6 = sm2.doSignature(msgString, privateKey, {
hash: true,
publicKey,
userId: 'testUserId',
})
let verifyResult6 = sm2.doVerifySignature(msgString, sigValueHex6, publicKey, {
hash: true,
userId: 'testUserId',
})

Obtain Elliptic Curve Point


let point = sm2.getPoint() // Obtain an Elliptic Curve Point, which can be passed in during SM2 Signing.

sm3


let hashData = sm3('abc') // Hashing

// hmac
hashData = sm3('abc', {
key: 'daac25c1512fe50f79b0e4526b93f5c0e1460cef40b6dd44af13caec62e8c60e0d885f3c6d6fb51e530889e6fd4ac743a6d332e68a0f2a3923f42585dceb93e9', // Required to be a hexadecimal string or a byte array.
})

sm4

Encryption

const msg = 'hello world! I'm juneandgreen.' // Can be a UTF-8 string or a byte array.

const key = '0123456789abcdeffedcba9876543210' // Can be a hexadecimal string or a byte array, required to be 128 bits.

let encryptData = sm4.encrypt(msg, key) // Encryption, default output is a hexadecimal string, default padding is PKCS#7 (passing PKCS#5 will also use PKCS#7 padding).

let encryptData = sm4.encrypt(msg, key, {padding: 'none'}) // Encryption, without padding.
let encryptData = sm4.encrypt(msg, key, {padding: 'none', output: 'array'}) // Encryption, no padding, output as a byte array.
let encryptData = sm4.encrypt(msg, key, {mode: 'cbc', iv: 'fedcba98765432100123456789abcdef'}) // Encryption, CBC (Cipher Block Chaining) mode.

Decryption

const encryptData = '0e395deb10f6e8a17e17823e1fd9bd98a1bff1df508b5b8a1efb79ec633d1bb129432ac1b74972dbe97bab04f024e89c' // Can be a hexadecimal string or byte array
const key = '0123456789abcdeffedcba9876543210' // Can be a hexadecimal string or byte array, required to be 128 bits

let decryptData = sm4.decrypt(encryptData, key) // Decrypt, default output is a UTF-8 string, default padding is PKCS#7 (passing PKCS#5 will also use PKCS#7 padding)
let decryptData = sm4.decrypt(encryptData, key, {padding: 'none'}) // Decrypt, no padding
let decryptData = sm4.decrypt(encryptData, key, {padding: 'none', output: 'array'}) // Decrypt, no padding, output as a byte array
let decryptData = sm4.decrypt(encryptData, key, {mode: 'cbc', iv: 'fedcba98765432100123456789abcdef'}) // Decrypt, CBC mode

$.md5()

A simple function to generate an MD5 encrypted string, example:

let md5Str = $.md5(123456);
console.log(md5Str) // 487f7b22f68312d2c1bbc93b1aea445b

sleep()

Delay function, example:

console.log(1)
sleep(2000)
console.log(2) // Will output after a delay of 2000 milliseconds.

console

Console output example:

console.log(123) // Outputs 123 to the EchoAPI console

validCookie

Verify whether a specified cookie is valid for a specified URL.

Usage Documentation

const cookie1 = {
name: 'foo',
value: 'bar',
path: '/site',
expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'),
maxAge: 1000,
domain: '.example.com',
secure: true,
httpOnly: true,
sameSite: 'lax'
},
cookie2 = {
name: 'foo',
value: 'bar',
path: '/site',
expires: new Date('Tue Jul 01 1979 06:01:11 GMT-0400 (EDT)'),
maxAge: 1000,
domain: '.example.com',
secure: true,
httpOnly: true,
sameSite: 'lax'
},
cookie3 = {
name: 'foo',
value: 'bar',
path: '/site',
expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'),
maxAge: 1000,
domain: '.not-example.com',
secure: true,
httpOnly: true,
sameSite: 'lax'
},
cookie4 = {
name: 'foo',
value: 'bar',
path: '/no-site',
expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'),
maxAge: 1000,
domain: '.not-example.com',
secure: true,
httpOnly: true,
sameSite: 'lax'
};
validCookie.isvalid('https://www.example.com/site', cookie1) //Meets the requirements, returns
/*
{
"cookie": "foo=bar",
"set-cookie": "foo=bar; Max-Age=1000; Domain=www.example.com; Path=/site/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure; SameSite=Lax"
}
*/

validCookie.isvalid('https://www.example.com/site', cookie2) //Does not meet the requirements, returns false.
validCookie.isvalid('https://www.example.com/site', cookie3) //Does not meet the requirements, returns false.
validCookie.isvalid('https://www.example.com/site', cookie4) //Does not meet the requirements, returns false.

urlJoin

Join all parameters together to return and standardize the URL.

Usage Documentation

const fullUrl = urlJoin('http://www.google.com', 'a', '/b/cd', '?foo=123');

console.log(fullUrl);

aTools

Utility toolkit.

Usage Documentation

let json='{"name":"I am an EchoAPI user"}';
let email='echoapi@gmail.com';

aTools.isJson(json); //true
aTools.isEmail(email); //true

//Currently supported:
array2Tree //Convert flat data to tree structure
beautifyRaw //Beautify data, currently supports object, xml, html, jsonp, javascript. The result is an object containing mode (type) and value (beautified result)
formatXml //Format XML data
getUrlQuery //Get query data in URL (object).
getUrlQueryArray //Get query data in URL (array).
isEmail //Verify email format
isXml //Check if it is XML format
isJson //Check if it is JSON format
isJson5 //Check if it is JSON5 format
isJsonp //Check if it is JSONP format
isHtml //Check if it is HTML format
ms2second //Convert millisecond timestamp to second timestamp
formatHtml //Format HTML data
jsonp2Obj //Convert JSONP format to object
errorResult //Unified error result object
successResult //Unified success result object
bufferToRaw //Convert buffer to raw
completionHttpProtocol //Complete the HTTP protocol header
NewURL //Generate a URL object based on the URL
caution

No need to reference built-in libraries using require/import; you can use them directly!