Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

@coolgk/utils

3.1.2 • Public • Published

Build Status dependencies Status Coverage Status Known Vulnerabilities

npm install @coolgk/utils

You can install and use the modules below as standalone packages. If you wish to use @coolgk/utils as an all-in-one package, replace @coolgk/[module] with @coolgk/utils/[module] in the require() or import statements in the examples below.

Report bugs here: https://github.com/coolgk/node-utils/issues

Also see:

@coolgk/mongo

A javascript / typescript MongoDB modelling library which enables joins in collections, simplifies CRUD operations for sub / nested documents and implements schema based data validation.

@coolgk/mvc

A simple, lightweight javascript / typescript MxC framework that helps you to create object oriented, modular and testable code.

@coolgk/amqp

a javascript / typescript module

npm install @coolgk/amqp

a simple RabbitMQ (amqp wrapper) class for publishing and consuming messages

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Amqp } from '@coolgk/amqp';
// OR
// const { Amqp } = require('@coolgk/amqp');
 
const amqp = new Amqp({
    url: 'amqp://localhost/vhost'
});
 
const message = {
    a: 1,
    b: 'b'
};
 
// CONSUMER MUST BE STARTED FIRST BEFORE PUSHLISHING ANY MESSAGE
 
// consumer.js
// consume message and return (send) a response back to publisher
amqp.consume(({rawMessage, message}) => {
    console.log('consumer received', message); // consumer received ignore response
                                               // consumer received { a: 1, b: 'b' }
    return {
        response: 'response message'
    }
});
 
// publisher.js
// publish a message, no response from consumer
amqp.publish('ignore response');
 
// publish a message and handle response from consumer
amqp.publish(message, ({rawResponseMessage, responseMessage}) => {
    console.log('response from consumer', responseMessage); // response from consumer { response: 'response message' }
});
 
 
// example to add:
// consume from (multiple) routes
// round robin consumers
// direct route + a catch all consumer
 

Amqp

Kind: global class

new Amqp(options)

Param Type Description
options object
options.url string connection string e.g. amqp://localhost
[options.sslPem] string pem file path
[options.sslCa] string sslCa file path
[options.sslPass] string password

amqp.closeConnection() ⇒ void

Kind: instance method of Amqp

amqp.publish(message, [callback], [options]) ⇒ promise.<Array.<boolean>>

Kind: instance method of Amqp

Param Type Default Description
message * message any type that can be JSON.stringify'ed
[callback] function callback(message) for processing response from consumers
[options] object
[options.routes] string | Array.<string> "['#']" route names
[options.exchangeName] string "'defaultExchange'" exchange name

amqp.consume(callback, [options]) ⇒ promise

Kind: instance method of Amqp

Param Type Default Description
callback function consumer(message) function should returns a promise
[options] object
[options.routes] string | Array.<string> "['#']" exchange routes
[options.queueName] string "''" queue name for processing messages. consumers with the same queue name process messages in round robin style
[options.exchangeName] string "'defaultExchange'" exchange name
[options.exchangeType] string "'topic'" exchange type
[options.priority] number 0 priority, larger numbers indicate higher priority
[options.prefetch] number 1 1 or 0, if to process request one at a time

amqp.getChannel() ⇒ promise

Kind: instance method of Amqp
Returns: promise - - promise

@coolgk/cache

a javascript / typescript module

npm install @coolgk/cache

a redis wrapper

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Cache } from '@coolgk/cache';
import { createClient } from 'redis';
// OR
// const { Cache } = require('@coolgk/cache');
// const { createClient } = require('redis');
 
const client = createClient({
    host: 'localhost',
    port: 12869,
    password: '----'
});
 
const cache = new Cache({
    redisClient: client
});
 
cache.set('abc', {a: 1}, 1).then(console.log); // 'OK'
 
cache.get('abc').then(console.log); // { a: 1 }
 
setTimeout(() => {
    cache.get('abc').then(console.log); // null
    client.quit();
}, 1500);
 
cache.getSetIfNull(
    'abc',
    () => Promise.resolve('data'),
    10
).then((v) => {
    console.log(v); // { a: 1 }
});
 
Promise.all([
    cache.set('x', 'val x'),
    cache.set('y', 'val y'),
    cache.set('z', 'val z')
]).then(
    () => Promise.all([
        cache.get('x').then(console.log), // val x
        cache.get('y').then(console.log), // val y
        cache.get('z').then(console.log) // val z
    ])
).then(
    () => Promise.all([
        cache.delete('x'),
        cache.delete('y'),
        cache.delete('z')
    ])
).then(
    () => Promise.all([
        cache.get('x').then(console.log), // null
        cache.get('y').then(console.log), // null
        cache.get('z').then(console.log) // null
    ])
);
 

Cache

Kind: global class

new Cache(options)

Param Type Description
options object
[options.redisClient] object redis client from redis.createClient() redisClient needs to be passed in so the same connection can be used elsewhere and get closed outside this class

cache.set(name, value, [expiry]) ⇒ promise

Kind: instance method of Cache

Param Type Default Description
name string name of the variable
value * value is always JSON.stringify'ed
[expiry] number 0 expire time in seconds. 0 = never expire

cache.get(name) ⇒ promise

Kind: instance method of Cache
Returns: promise - - cached value

Param Type Description
name string name of the variable

cache.delete(name) ⇒ promise

Kind: instance method of Cache

Param Type Description
name string | Array.<string> name(s) of the variable

cache.getSetIfNull(name, callback, [expiry]) ⇒ promise

get the cached value, if not set, resolve "callback()" and save the value then return it

Kind: instance method of Cache
Returns: promise - - cached value

Param Type Default Description
name string name of the variable
callback function a callback function which returns a value or a promise
[expiry] number 0 expire time in seconds. 0 = never expire

cache.command(command, ...params) ⇒ promise

Kind: instance method of Cache

Param Type Description
command string redis command to run
...params array params for the command

@coolgk/bcrypt

a javascript / typescript module

npm install @coolgk/bcrypt

just a promise wrapper

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { encrypt, verify } from '@coolgk/bcrypt';
// OR
// const { encrypt, verify } = require('@coolgk/bcrypt');
 
const password = 'abc123';
 
encrypt(password).then((hash) => {
    verify(password, hash).then(console.log); // true
    verify(password, 'invalidhash').then(console.log, console.error); // Not a valid BCrypt hash.
    verify('invalidpass', hash).then(console.log); // false
});
 

Functions

encrypt(value, salt)promise.<string>
verify(value, hashedString)promise.<boolean>

encrypt(value, salt) ⇒ promise.<string>

Kind: global function

Param Type Description
value string string to encrypt
salt string salt

verify(value, hashedString) ⇒ promise.<boolean>

Kind: global function

Param Type Description
value string string to check
hashedString string encrypted hash

@coolgk/captcha

a javascript / typescript module

npm install @coolgk/captcha

recapcha wrapper

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

const { verify } = require('@coolgk/captcha');
const secret = '-------';
 
verify(secret, captchaResponse).then((response) => {
    console.log(response); // { success: true, challenge_ts: '2017-12-03T08:19:48Z', hostname: 'www.google.com' }
                           // { success: false, 'error-codes': [ 'invalid-input-response' ] }
});
 
// OR
 
import { Captcha } from '@coolgk/captcha';
// OR
// const { Captcha } = require('@coolgk/captcha');
 
const captcha = new Captcha({ secret });
 
const captchaResponse = '---------';
 
captcha.verify(captchaResponse).then((response) => {
    console.log(response); // { success: true, challenge_ts: '2017-12-03T08:19:48Z', hostname: 'www.google.com' }
                           // { success: false, 'error-codes': [ 'invalid-input-response' ] }
});
 

Captcha

Kind: global class

new Captcha(options)

Param Type Description
options object
options.secret object google captcha secret https://www.google.com/recaptcha/admin#site/337294176

captcha.verify(response, [remoteip])

Kind: instance method of Captcha

Param Type Description
response string repsonse from recaptcha
[remoteip] string ip address
promise

@coolgk/email

a javascript / typescript module

npm install @coolgk/email

a email sender wrapper class

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Email } from '@coolgk/email';
// OR
// const { Email } = require('@coolgk/email');
 
const email = new Email({host: 'localhost'});
 
email.send({
    subject: 'hello this is email subject',
    from: {
            name: 'Daniel Gong',
            email: 'daniel.k.gong@example.com'
    },
    to: [
        {
            name: 'Dan Go',
            email: 'dan@example.com'
        },
        'gong@example.com'
    ],
    message: '<html><body><h1>test</h1>some message here <img src="cid:my-image" width="500" height="250"></body></html>',
    attachments: [
        {
            path: '/tmp/test.png',
            name: 'screenshot.png'
        },
        {
            path:"/tmp/test.png",
            headers:{"Content-ID": "<my-image>"}
        }
    ]
}).then((sentMessage) => {
    console.log(sentMessage);
}).catch((error) => {
    console.log(error);
});
 

Email

Kind: global class
See: https://www.npmjs.com/package/emailjs#emailserverconnectoptions

new Email(options)

Param Type Default Description
options object
[options.user] string username for logging into smtp
[options.password] string password for logging into smtp
[options.host] string "'localhost'" smtp host
[options.port] string smtp port (if null a standard port number will be used)
[options.ssl] boolean boolean (if true or object, ssl connection will be made)
[options.tls] boolean boolean (if true or object, starttls will be initiated)
[options.domain] string domain to greet smtp with (defaults to os.hostname)
[options.authentication] Array.<string> authentication methods

email.send(options, [attachments]) ⇒ promise

Kind: instance method of Email
Returns: promise - - message sent

Param Type Description
options object
options.subject string email subject
[options.message] string html email message
options.to Array.<(string|object)> to email address
options.to[].name string name of the recipient
options.to[].email string email address of the recipient
[options.from] string | object see options.to
[options.cc] Array.<(string|object)> see options.to
[options.bcc] Array.<(string|object)> see options.to
[attachments] Array.<object> email attachments
attachments.path string file path
[attachments.name] string file name
[attachments.type] string file mime type
[attachments.method] string method to send attachment as (used by calendar invites)
[attachments.headers] object attachment headers, header: value pairs, e.g. {"Content-ID":""}

@coolgk/facebook-sign-in

a javascript / typescript module

npm install @coolgk/facebook-sign-in

facebook sign in module which verifies client access token and returns account data

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

const { FacebookSignIn } = require('@coolgk/facebook-sign-in');
// OR
// import { FacebookSignIn } from '@coolgk/facebook-sign-in';
 
const facebookSignIn = new FacebookSignIn({
    clientId: '...',
    secret: '...'
});
 
const invalidToken = '...';
const validToken = '...';
 
(async () => {
    const account1 = await facebookSignIn.verify(invalidToken);
    console.log(account1); // false
 
    const account2 = await facebookSignIn.verify(validToken);
    console.log(account2); // { email: 'abc@example.com', id: '123123123123123123' }
})()
 

FacebookSignIn

Kind: global class
Export:

facebookSignIn.verify(token, [fields]) ⇒ Promise.<(false|object)>

verify access token from clients and return false or account data

Kind: instance method of FacebookSignIn
Returns: Promise.<(false|object)> - - false if access token is invalid otherwise returns account data

Param Type Default Description
token string facebook user's token string
[fields] string "'email'" fields to fetch from user's facebook account. comma separated value e.g. id,name,email

FacebookSignIn.FacebookSignIn

Kind: static class of FacebookSignIn

new FacebookSignIn(options)

Param Type Description
options object
options.clientId string facebook app id
options.secret string facebook app secret

@coolgk/csv

a javascript / typescript module

npm install @coolgk/csv

read and write csv files

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Csv } from '@coolgk/csv';
// OR
// const { Csv } = require('@coolgk/csv');
 
const csv = new Csv({
    tmpConfig: { dir: '/tmp/csv' } // optional
});
 
const arrayData = [
    [1,2,3,4,5],
    [6,7,7,8,9],
    [0,5,8,90,65]
];
 
const objectData = [
    {col1: 'ab', col2: 'cd', col3: 'ef'},
    {col1: '2ab', col2: '2cd', col3: '2ef'},
    {col1: '3ab', col2: '3cd', col3: '3ef'}
];
 
csv.createFile(
    arrayData,
    {
        columns: ['column 1', 'column 2', 'column 3', 'h4', 'h5'],
        formatter: (row) => {
            return row.map((value) => 'formatted-' + value);
        }
    }
).then((csvFilePath) => {
    console.log(csvFilePath); // /tmp/csv/151229255018910356N9qKqUgrpzG2.csv
    read(csvFilePath, ['column 1', 'column 2', 'column 3', 'h4', 'h5']);
});
 
csv.createFile(
    objectData,
    {
        columns: ['col1', 'col2', 'col3'],
        formatter: (row) => {
            return [row.col1 + '+format', row.col2 + '+format', row.col3 + '+format'];
        }
    }
).then((csvFilePath) => {
    console.log(csvFilePath); // /tmp/csv/151229255019910356AlO9kbzkdqjq.csv
    read(csvFilePath, ['col1', 'col2', 'col3']);
});
 
function read (file, columns) {
    // with columns/headers
    // read lines as object
    const lines = csv.readFile(file, {columns: columns});
    lines.forEach(
        (lineArray, index) => {
            console.log(lineArray, index);
            // {
                // 'column 1': 'formatted-1',
                // 'column 2': 'formatted-2',
                // 'column 3': 'formatted-3',
                // h4: 'formatted-4',
                // h5: 'formatted-5'
            // } 1
        },
        (total) => {
            console.log('read done, total:', total); // read done, total: 4
        }
    );
 
    // without columns/headers
    // read lines as array
    const lines2 = csv.readFile(file);
    lines2.forEach(
        (lineArray, index) => {
            console.log(lineArray, index); // [ 'formatted-1', 'formatted-2', 'formatted-3', 'formatted-4', 'formatted-5' ] 1
        },
        (total) => {
            console.log('read done, total:', total); // read done, total: 4
        }
    );
}
 

Csv

Kind: global class

new Csv([options])

Param Type Default Description
[options] object
[options.tmpConfig] object config for the generated file
[options.tmpConfig.mode] number 0600 the file mode to create with, defaults to 0600 on file and 0700 on directory
[options.tmpConfig.prefix] string "Date.now()" the optional prefix
[options.tmpConfig.dir] string "os.tmpdir()" the optional temporary directory, fallbacks to system default

csv.parse(value, [options]) ⇒ promise.<array>

parse a string as csv data and returns an array promise

Kind: instance method of Csv

Param Type Default Description
value string a csv string
[options] object
[options.columns] Array.<string> array of headers e.g. ['id', 'name', ...] if headers is defined, the row value will be objects
[options.limit] number 0 number of rows to read, 0 = unlimited
[options.delimiter] string "','" csv delimiter

csv.readFile(file, [options]) ⇒ object

read a csv file. the return value can ONLY be used in a forEach() loop e.g. readFile('abc.csv').forEach((row, index) => { console.log(row, index) })

Kind: instance method of Csv
Returns: object - - { forEach: ((row, index) => void, (totalCount) => void) => void }

Param Type Default Description
file string file path
[options] object
[options.columns] Array.<string> array of headers e.g ['id', 'name', ...] if defined, rows become objects instead of arrays
[options.limit] number 0 number of rows to read, 0 = unlimited
[options.delimiter] string "','" csv delimiter

csv.createFile(data, [options]) ⇒ promise.<string>

Kind: instance method of Csv
Returns: promise.<string> - - file path of the csv file generated

Param Type Default Description
data array | cursor mongo cursor or array of data
[options] object
[options.columns] Array.<string> array of headers e.g. ['id', 'name', 'email']
[options.formatter] function callback for formatting row data. It takes one row from data as parameter and should return an array e.g. (rowData) => [rowData.id, rowData.name, 'formatted data'],
[options.delimiter] string "','" Set the field delimiter, one character only, defaults to a comma.
[options.filepath] string file path is automatically generated if empty

@coolgk/formdata

a javascript / typescript module

npm install @coolgk/formdata

A http request form data parser (large file friendly) for 'application/json', 'application/x-www-form-urlencoded' and 'multipart/form-data'. It only parses form data when you ask for it.

Report bugs here: https://github.com/coolgk/node-utils/issues

Example Form

<form method="POST" enctype="multipart/form-data">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="file" name="photo">
    <input type="file" name="photo">
    <input type="file" name="id">
</form>

Express Middleware

// express middleware
const app = require('express')();
const formdata = require('@coolgk/formdata');
 
app.use(formdata.express());
 
app.post('/id-only', async (request, response, next) => {
    const post = await request.formdata.getData('id'); // upload 3 files but only parse 1, ignore others
    console.log(post);
    response.json(post);
    // output
    // {
        // "name": "Tim",
        // "age": "33",
        // "id": {
            // "error": null,
            // "fieldname": "id",
            // "filename": "test.txt",
            // "encoding": "7bit",
            // "mimetype": "text/plain",
            // "size": 13,
            // "path": "/tmp/151605931497716067xZGgxPUdNvoj"
        // }
    // }
});
 
app.post('/all-files', async (request, response, next) => {
    const post = await request.formdata.getData(['id', 'photo']); // parse all files
    console.log(post);
    response.json(post);
    // output
    // {
        // "name": "Tim",
        // "age": "33",
        // "photo": [
            // {
                // "error": null,
                // "fieldname": "photo",
                // "filename": "test.png",
                // "encoding": "7bit",
                // "mimetype": "image/png",
                // "size": 604,
                // "path": "/tmp/151605931497716067xZGgxPUdNvoj"
            // },
            // {
                // "error": null,
                // "fieldname": "photo",
                // "filename": "test.svg",
                // "encoding": "7bit",
                // "mimetype": "image/svg+xml",
                // "size": 2484,
                // "path": "/tmp/151605931497916067EAUAa3yB4q42"
            // }
        // ],
        // "id": {
            // "error": null,
            // "fieldname": "id",
            // "filename": "test.txt",
            // "encoding": "7bit",
            // "mimetype": "text/plain",
            // "size": 13,
            // "path": "/tmp/151605931498016067zqZe6dlhidQ5"
        // }
    // }
});
 
app.listen(8888);

Native Node App

const { formData, express, getFormData, FormDataError } = require('@coolgk/formdata');
const http = require('http');
http.createServer(async (request, response) => {
 
    const data = await getFormData(request, { fileFieldNames: ['id', 'photo'] });
 
    // OR
    // const formdata = formData(request);
    // ... some middelware
    // ... in some routes
    // const data = formdata.getData(['id', 'photo']);
 
    console.log(data);
    response.end(JSON.stringify(data));
 
    // {
        // "name": "Tim",
        // "age": "33",
        // "photo": [
            // {
                // "error": null,
                // "fieldname": "photo",
                // "filename": "test.png",
                // "encoding": "7bit",
                // "mimetype": "image/png",
                // "size": 604,
                // "path": "/tmp/151605931497716067xZGgxPUdNvoj"
            // },
            // {
                // "error": null,
                // "fieldname": "photo",
                // "filename": "test.svg",
                // "encoding": "7bit",
                // "mimetype": "image/svg+xml",
                // "size": 2484,
                // "path": "/tmp/151605931497916067EAUAa3yB4q42"
            // }
        // ],
        // "id": {
            // "error": null,
            // "fieldname": "id",
            // "filename": "test.txt",
            // "encoding": "7bit",
            // "mimetype": "text/plain",
            // "size": 13,
            // "path": "/tmp/151605931498016067zqZe6dlhidQ5"
        // }
    // }
 
}).listen(8888);

Constants

FormDataError : object

Error Codes

Functions

getFormData(request, [options])promise.<{}>

the return value contains all normal post fields and the file upload fields that in "fileFieldNames" param

formData(request, [globalOptions])object
express([options])function

FormDataError : object

Error Codes

Kind: global constant
Properties

Name Type Description
FILE_SIZE_EXCEEDED_LIMIT string size of uploaded file exceeded limit
NUM_OF_NON_FILE_FIELDS_EXCEEDED_LIMIT string # of non file fields exceeded limit
NUM_OF_FIELDS_EXCEEDED_LIMIT string # of fields posted exceeded limit
NUM_OF_FILES_EXCEEDED_LIMIT string # of file fields exceeded limit
POST_SIZE_EXCEEDED_LIMIT string the max number of bytes exceeded limit for application/json & application/x-www-form-urlencoded
FIELD_SIZE_EXCEEDED_LIMIT string max field value size exceeded limit
INVALID_JSON string invalid json data for application/json

getFormData(request, [options]) ⇒ promise.<{}>

the return value contains all normal post fields and the file upload fields that in "fileFieldNames" param

Kind: global function
Returns: promise.<{}> - - { fieldname: value, uploadedFileName: { error: ..., fieldname: ..., filename: ..., encoding: ..., mimetype: ..., size: ..., path: ..., remove: () => void } } "remove" is a callback function for deleting the uploaded file

Param Type Default Description
request object the request object in http.createServer() callback or express request
[options] object
[options.array] boolean false if to always get form data as array. By default values could either be string or array e.g. fieldname = val1, fieldname = [val1, val2]. if array is true, fieldname = val1 becomes fieldname = [val1]
[options.fileFieldNames] Array.<string> | string name of the file upload fields. Only file fields in this list are parsed, other files are ignored i.e. if someone sends a random huge file onto your server, it will not be stored in disk or memory.
[options.mode] number 0600 permission of the uploaded files, defaults to 0600 on file and 0700 on directory
[options.prefix] string "Date.now()" prefix for file names
[options.postfix] string "''" postfix for file names
[options.dir] string "os.tmpdir()" directory for storing the uploaded files, fallbacks to system default
[options.alwaysReject] boolean false if to reject the promise when fieldNameSize and fieldSize limits are exceeded. By default, field name and value will be truncated to their limits. 'multipart/form-data' only
[options.limits] object
[options.limits.fieldSize] string 1024000 Max field value size (in bytes) (Default: 1MB), 'multipart/form-data' only
[options.limits.fields] string "Infinity" Max number of non-file fields (Default: Infinity)
[options.limits.fileSize] string "Infinity" the max file size (in bytes) (Default: Infinity)
[options.limits.files] string "Infinity" the max number of file fields (Default: Infinity)
[options.limits.parts] string "Infinity" the max number of parts (fields + files) (Default: Infinity), 'multipart/form-data' only
[options.limits.headerPairs] string 2000 For multipart forms, the max number of header key=>value pairs to parse Default: 2000 (same as node's http)
[options.limits.postSize] string 1024000 the max number of bytes can be posted. For application/json & application/x-www-form-urlencoded only

formData(request, [globalOptions]) ⇒ object

Kind: global function
Returns: object - - { getData: (fileFieldNames, options) => ... } see "fileFieldNames" and "options" and the return value of getFormData()
See: getFormData()

Param Type Description
request object http.IncomingMessage, request parameter in createServer()'s callback or express request
[globalOptions] object see the "option" param of getFormData()

express([options]) ⇒ function

Kind: global function
Returns: function - - (request, response, next) => ... see the return value of getFormData()
See: getFormData()

Param Type Default Description
[options] object see the "option" param of getFormData()
[options.requestFieldName] object 'formdata' field name to be assigned to the request object. by default it assigns to request.formdata

@coolgk/jwt

a javascript / typescript module

npm install @coolgk/jwt

a simple jwt token class

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Jwt } from '@coolgk/jwt';
// OR
// const { Jwt } = require('@coolgk/jwt');
 
const jwt = new Jwt({secret: 'abc'});
 
const string = 'http://example.com/a/b/c?a=1';
 
const token = jwt.generate(string);
 
console.log(
    jwt.verify(token), // { exp: 0, iat: 1512307492763, rng: 0.503008668963175, data: 'http://example.com/a/b/c?a=1' }
    jwt.verify(token+'1') // false
);
 
const token2 = jwt.generate(string, 200);
 
console.log(
    jwt.verify(token2), // { exp: 1512307493026, iat: 1512307492826, rng: 0.5832258275608753, data: 'http://example.com/a/b/c?a=1' }
    jwt.verify(token+'1') // false
);
 
setTimeout(() => {
    console.log(jwt.verify(token2)); // false
}, 250);
 

Jwt

Kind: global class

new Jwt(options)

Param Type Description
options object
options.secret string for encryption

jwt.generate(data, [expiry]) ⇒ string

Kind: instance method of Jwt

Param Type Default Description
data * any data can be JSON.stringify'ed
[expiry] number 0 in milliseconds 0 = never expire

jwt.verify(token) ⇒ boolean | object

Kind: instance method of Jwt
Returns: boolean | object - - false or the payload of the token

Param Type Description
token string token to verify

@coolgk/number

a javascript / typescript module

npm install @coolgk/number

number utitlies

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { round } from '@coolgk/number';
// OR
// const { round } = require('@coolgk/number');
 
console.log(round(1.3923, 2)); // 1.39
console.log(round(100, 2)); // 100
console.log(round(100.1264, 2)); // 100.13
console.log(round(100.958747, 4)); // 100.9587
 

round(value, precision) ⇒ number

Kind: global function

Param Type Default Description
value number number to round
precision number 2 precision

@coolgk/queue

a javascript / typescript module

npm install @coolgk/queue

This is a super lightweight function that limits the number of async functions run concurrently and run them in order.

Report bugs here: https://github.com/coolgk/node-utils/issues

  1. Put async functions in a queue and limit the number of async functions that run concurrently.
  2. Run async functions in order
  3. Run x number of functions in parallel per batch in order. similar to async / await when the second parameter is 1.

Examples

import { queue } from '@coolgk/queue';
// OR
// const { queue } = require('@coolgk/queue');
 
function a (x) {
    console.log('start a');
    return new Promise((resolve) => setTimeout(() => { console.log('end a', x); resolve('a') }, 1300));
}
 
function b (x) {
    console.log('start b');
    return new Promise((resolve) => setTimeout(() => { console.log('end b', x); resolve('b') }, 1200));
}
 
function c (x) {
    console.log('start c');
    return new Promise((resolve) => setTimeout(() => { console.log('end c', x); resolve('c') }, 100));
}
 
// call a, b, c in order i.e. b does not start until a resolves
queue(a);
queue(b);
queue(c);
 
// call a 5 times, each waits until the previous call resolves
[1,2,3,4,5].forEach(() => {
    queue(a)
});
 
// run 3 jobs at a time
[1,2,3,4,5,6,7,8,9,10].forEach(() => {
    queue(a, 3)
});
 

queue(callback, [limit]) ⇒ promise

Kind: global function

Param Type Default Description
callback function callback function that returns a promise or any other types
[limit] number 1 number of callback to run at the same time, by default one callback at a time

@coolgk/pdf

a javascript / typescript module

npm install @coolgk/pdf

html to PDF module. create PDF files from html string or file.

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

// for "error while loading shared libraries: libfontconfig.so" run "sudo apt-get -y install libfontconfig"
 
import { Pdf, Format, Orientation } from '@coolgk/pdf';
// OR
// const { Pdf, Format, Orientation } = require('@coolgk/pdf');
 
const pdf = new Pdf({
    tmpConfig: { dir: '/tmp/pdf' } // optional
});
 
pdf.createFromHtmlFile(
    '/tmp/test.html',
    {
        header: {
            height: '1cm',
            contents: "<strong style='color: red'>Page ${pageNumber} of ${numberOfPages} - ${pageNumber}</strong>"
        },
        footer: {
            height: '1cm',
            contents: 'footer <strong>Page ${pageNumber} of ${numberOfPages}</strong>'
        },
        margin: '0.5cm'
    }
).then((pdfFile) => {
    console.log(pdfFile);
});
 
const htmlCode = `<!DOCTYPE html><html><head>
        <title>CCES</title>
        <style>
            .pagebreak { page-break-after: always; }
            h2, h1 { color: red }
        </style>
    </head>
    <body>
        <div>
            <h1>page 1</h1>
            <p>some text <img src='https://dummyimage.com/600x400/3bbda9/f516ae.jpg'></p>
        </div>
        <div class="pagebreak"></div>
        <div>
            <h2>page 2</h2>
            <table>
                <tr>
                    <td>texgt</td>
                    <td>text</td>
                </tr>
            </table>
        </div>
    </body>
</html>`;
 
pdf.createFromHtmlString(htmlCode).then((pdfFile) => {
    console.log(pdfFile);
});
 

Pdf

Kind: global class

new Pdf([options])

Param Type Default Description
[options] object
[options.tmpConfig] object config for the generated file
[options.tmpConfig.mode] number 0600 the file mode to create with, defaults to 0600 on file and 0700 on directory
[options.tmpConfig.prefix] string "Date.now()" the optional prefix
[options.tmpConfig.dir] string "os.tmpdir()" the optional temporary directory, fallbacks to system default

pdf.createFromHtmlFile(htmlFilePath) ⇒ promise.<string>

Kind: instance method of Pdf
Returns: promise.<string> - - filepath of the generated PDF
See: http://phantomjs.org/api/webpage/property/paper-size.html A4 page height: 842px for full page in PDF, set height of a page in html to 842px

Param Type Default Description
htmlFilePath string file path of an html
[options.pdfFilePath] string file path is automatically generated if empty
[options.delay] number 1 delay in seconds before generating pdf. wait for js generated contents.
[options.margin] string | number 0 e.g. 1cm or {top: '50px', left: '20px'}
[options.orientation] string "'portrait'" e.g. portrait or landscape
[options.format] string "'A4'" e.g. A4
[options.header] string | object html code e.g. Page ${pageNumber} of ${numberOfPages}
[options.header.height] string | number e.g. 1cm or 100px
[options.header.contents] string html code e.g. Page ${pageNumber} of ${numberOfPages}
[options.footer] string | object html code e.g. Page ${pageNumber} of ${numberOfPages}
[options.footer.height] string | number e.g. 1cm or 100px
[options.footer.contents] string | number e.g. html code e.g. Page ${pageNumber} of ${numberOfPages}
[options.dpi] number 96 e.g. 96

pdf.createFromHtmlString(htmlString, [options]) ⇒ promise

Kind: instance method of Pdf
Returns: promise - - filepath of the generated PDF
See: createFromHtmlFile()

Param Type Description
htmlString string html code e.g. <h1>header 1</h1>
[options] object see options in createFromHtmlFile()

@coolgk/session

a javascript / typescript module

npm install @coolgk/session

An session handler that works without cookie (and with cookie too).

Report bugs here: https://github.com/coolgk/node-utils/issues

When working without cookie, this class reads the session token from the "Authorization" header. e.g. Authorization : Bearer cn389ncoiwuencr...

Express Middleware Example

// express middleware
const session = require('@coolgk/session');
const app = require('express')();
 
app.use(
    session.express({
        redisClient: require('redis').createClient({
            host: process.env.REDIS_HOST,
            port: process.env.REDIS_PORT,
            password: process.env.REDIS_PASSWORD
        }),
        secret: '123' // secret is required for creating the session token / id
    })
);
 
app.use(async (request, response, next) => {
    // allow access if it's the login page or the request has a valid session
    if ('/login' === request.url || await request.session.verifyAndRenew()) { // if session is verified, renew session
        next();
    } else { // deny access
        response.send('Please Login');
        // output
        // 'Please Login'
    }
});
 
app.get('/login', async (request, response, next) => {
    // start a new session (create a new session id)
    const accessToken = await request.session.init();
    // set session variables
    await request.session.set('user', { id: 1, username: 'abc' });
    // send session token/id back
    response.json({ accessToken });
    // output
    // {"accessToken":"eyJleHAiOjAsIml..."}
});
 
app.get('/user', async (request, response, next) => {
    // get session variable
    response.json(await request.session.get('user'));
    // output
    // {"id":1,"username":"abc"}
});
 
app.get('/session', async (request, response, next) => {
    // get all session values
    response.json(await request.session.getAll());
    // output
    // {"user":{"id":1,"username":"abc"}}
});
 
app.get('/logout', async (request, response, next) => {
    // destroy current session
    await request.session.destroy();
    response.json(await request.session.getAll());
    // output
    // {}
});
 
app.listen(8888);

Native Node App Example

import { Session } from '@coolgk/session';
// OR
// const { Session } = require('@coolgk/session');
 
const http = require('http');
http.createServer(async (request, response) => {
 
    const session = new Session({
        redisClient: require('redis').createClient({
            host: process.env.REDIS_HOST,
            port: process.env.REDIS_PORT,
            password: process.env.REDIS_PASSWORD
        }),
        secret: '123',
        request,
        response
    });
 
    // ... some middelware
    // ... in some routes
    // set sesstion
    await session.start();
    await session.set('user', {id: 1, username: 'user@example.com'});
 
    // check session and renew if verified
    const verified = await session.verifyAndRenew();
    if (verified) {
        // session exists, logged in, do something
    } else {
        // deny access or show login screen
    }
 
    // show session data
    response.end(
        JSON.stringify(
            await session.getAll()
        )
    ); // {"user":{"id":1,"username":"user@example.com"}}
 
}).listen(8888);

To use without cookie

Create a session without the "response" property and the sessoin object will read the session id from the "Authorization" header i.e. Authorization : Bearer cn389ncoiwuencr...

const session = new Session({
    redisClient: require('redis').createClient({
        host: process.env.REDIS_HOST,
        port: process.env.REDIS_PORT,
        password: process.env.REDIS_PASSWORD
    }),
    secret: '123',
    request
});

Session

This class extends @coolgk/token see set(), get(), delete(), getAll() in @coolgk/token

Kind: global class

new Session(options)

Param Type Default Description
options object
options.redisClient object redis client from redis.createClient()
options.secret string a string for encrypting the session token
options.request object the request object in http.createServer() or express request
[options.expiry] expiry 3600 session expiry time in seconds
[options.response] object the response object in http.createServer() or express response. cookie will be set if the response property is set in the constructor.
[options.cookie] object cookie options
[options.cookie.domain] string Specifies the value for the Domain Set-Cookie attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
[options.cookie.encode] function encodeURIComponent Specifies a function that will be used to encode a cookie's value. Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.
[options.cookie.expires] date Specifies the Date object to be the value for the Expires Set-Cookie attribute. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
[options.cookie.httpOnly] boolean Specifies the boolean value for the [HttpOnly Set-Cookie attribute][rfc-6266-5.2.6]. When truthy, the HttpOnly attribute is set, otherwise it is not. By default, the HttpOnly attribute is not set.
[options.cookie.maxAge] number Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute. The given number will be converted to an integer by rounding down. By default, no maximum age is set.
[options.cookie.path] string "'/'" Specifies the value for the Path Set-Cookie attribute.
[options.cookie.sameSite] string | boolean Specifies the boolean or string to be the value for the SameSite Set-Cookie attribute
[options.cookie.secure] boolean Specifies the boolean value for the [Secure Set-Cookie attribute][rfc-6266-5.2.5]. When truthy, the Secure attribute is set, otherwise it is not. By default, the Secure attribute is not set.

session.init(signature) ⇒ promise.<string>

initialising a new session

Kind: instance method of Session
Returns: promise.<string> - - a session token string

Param Type Description
signature object addtional data for verifying session token e.g. an IP address. you can pass the IP address of an request to the verify() method and it will return false if the IP is different from the IP used for initialisng the session.

session.rotate(signature) ⇒ promise.<string>

rotate a session: start a new session and transfer old session values to the new session

Kind: instance method of Session
Returns: promise.<string> - - a session token string

Param Type Description
signature object addtional data for verifying session token e.g. an IP address. you can pass the IP address of an request to the verify() method and it will return false if the IP is different from the IP used for initialisng the session.

session.start(signature) ⇒ promise.<string>

start session: renew the existing session or if not valid valid session, start a new one

Kind: instance method of Session
Returns: promise.<string> - - a session token string

Param Type Description
signature object addtional data for verifying session token e.g. an IP address. you can pass the IP address of an request to the verify() method and it will return false if the IP is different from the IP used for initialisng the session.

session.destroy() ⇒ promise

destory the current session

Kind: instance method of Session

session.verify(signature) ⇒ promise.<boolean>

verify the session token

Kind: instance method of Session

Param Type Description
signature object addtional data for verifying session token e.g. an IP address. you can pass the IP address of an request to the verify() method and it will return false if the IP is different from the IP used for initialisng the session.

session.verifyAndRenew(signature, [expiry]) ⇒ promise.<boolean>

verify and renew token, renew only if token is valid (has a valid signature) and not expired

Kind: instance method of Session

Param Type Description
signature object addtional data for verifying session token e.g. an IP address. you can pass the IP address of an request to the verify() method and it will return false if the IP is different from the IP used for initialisng the session. verify the session token, if valid, renew this token
[expiry] number in seconds

session.renew([expiry]) ⇒ promise

renew session optionally with a different expiry time

Kind: instance method of Session
Returns: promise - - false if session has not been started or has a invalid token string

Param Type Description
[expiry] number in seconds

@coolgk/string

a javascript / typescript module

npm install @coolgk/string

string utility functions

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { stripTags, escapeHtml, unescapeHtml, prepad0 } from '@coolgk/string';
// OR
// const { stripTags, escapeHtml, unescapeHtml, prepad0 } = require('@coolgk/string');
 
const str = '<h1>test</h1><script>alert(1)</script>'
 
console.log(stripTags(str)); //  test alert(1)
console.log(escapeHtml(str)); // &lt;h1&gt;test&lt;/h1&gt;&lt;script&gt;alert(1)&lt;/script&gt;
console.log(unescapeHtml(escapeHtml(str))); // <h1>test</h1><script>alert(1)</script>
 
console.log(prepad0(7, 2)); // 07
console.log(prepad0(70, 3)); // 070
console.log(prepad0(70, 4)); // 0070
console.log(prepad0(1, 4)); // 0001
console.log(prepad0(1000, 2)); // 1000
 

Functions

stripTags(a)string

strip html tags e.g. "<h1>header</h1><p>message</p>" becomes "header message"

escapeHtml(value)string

escaping user input e.g. html code in a message box

unescapeHtml(string)string

unescaping strings escaped by escapeHtml()

prepad0(value, length)string

use padStart instead

stripTags(a) ⇒ string

strip html tags e.g. "<h1>header</h1><p>message</p>" becomes "header message"

Kind: global function
Returns: string - - string with tags stripped

Param Type Description
a string string

escapeHtml(value) ⇒ string

escaping user input e.g. html code in a message box

Kind: global function

Param Type Description
value string string to escape

unescapeHtml(string) ⇒ string

unescaping strings escaped by escapeHtml()

Kind: global function

Param Type Description
string string string to unescape

prepad0(value, length) ⇒ string

use padStart instead

Kind: global function
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

Param Type Default Description
value number an integer in string or number format
length number 2 length of the output e.g. length = 2, 8 becomes 08. length = 3, 70 = 070.

@coolgk/tmp

a javascript / typescript module

npm install @coolgk/tmp

wrapper functions, generate tmp file or folders

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { generateFile, generateDir, generateTmpName } from '@coolgk/tmp';
// OR
// const { generateFile, generateDir, generateTmpName } = require('@coolgk/tmp');
 
generateFile({dir: '/tmp/test'}).then((r) => console.log('file', r));
    // file { path: '/tmp/test/1512307052908140480ZZj6J0LOIJb.tmp' }
 
generateDir({dir: '/tmp/test'}).then((r) => console.log('dir',r));
    // dir { path: '/tmp/test/1512307052918140484Pnv1m95ZS2b' }
 
generateTmpName({dir: '/tmp/test'}).then((r) => console.log('name', r));
    // name { path: '/tmp/test/151230705292114048hb3XIds0FO9Y' }
 

Functions

generateFile([options])promise
generateDir([options])promise
generateTmpName([options])promise

generateFile([options]) ⇒ promise

Kind: global function
Returns: promise - - { path: ..., cleanupCallback: ... } calling cleanupCallback() removes the generated file

Param Type Default Description
[options] object
[options.mode] number 0600 the file mode to create with, defaults to 0600 on file and 0700 on directory
[options.prefix] string "Date.now()" the optional prefix, fallbacks to tmp- if not provided
[options.postfix] string "'.tmp'" the optional postfix, fallbacks to .tmp on file creation
[options.dir] string "/tmp" the optional temporary directory, fallbacks to system default
[options.keep] boolean false if to keep the file

generateDir([options]) ⇒ promise

Kind: global function
Returns: promise - - { path: ..., cleanupCallback: ... } calling cleanupCallback() removes the generated file

Param Type Default Description
[options] object
[options.mode] number 0600 the file mode to create with, defaults to 0600 on file and 0700 on directory
[options.prefix] string "Date.now()" the optional prefix, fallbacks to tmp- if not provided
[options.postfix] string "'.tmp'" the optional postfix, fallbacks to .tmp on file creation
[options.dir] string "/tmp" the optional temporary directory, fallbacks to system default
[options.keep] boolean false if to keep the file

generateTmpName([options]) ⇒ promise

Kind: global function
Returns: promise - - { path: ... }

Param Type Default Description
[options] object
[options.mode] number 0600 the file mode to create with, defaults to 0600 on file and 0700 on directory
[options.prefix] string "Date.now()" the optional prefix, fallbacks to tmp- if not provided
[options.postfix] string "'.tmp'" the optional postfix, fallbacks to .tmp on file creation
[options.dir] string "/tmp" the optional temporary directory, fallbacks to system default

@coolgk/google-sign-in

a javascript / typescript module

npm install @coolgk/google-sign-in

google sign in module which verifies id token and returns account data

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

const { GoogleSignIn } = require('@coolgk/google-sign-in');
// OR
// import { GoogleSignIn } from '@coolgk/google-sign-in';
 
const googleSignIn = new GoogleSignIn({
    clientId: '......'
});
 
const invalidToken = '...';
const validToken = '...';
 
(async () => {
    const account1 = await googleSignIn.verify(invalidToken);
    console.log(account1); // false
 
    const account2 = await googleSignIn.verify(validToken);
    console.log(account2);
    // {
    //     azp: '...',
    //     aud: '...',
    //     sub: '123123123',
    //     email: 'abc@exmaple.com',
    //     email_verified: true,
    //     at_hash: 'asdfasdfasdfasdfa',
    //     exp: 1520633389,
    //     iss: 'accounts.google.com',
    //     jti: 'qfwfasdfasdfasdfasdfasdfasdfadsf',
    //     iat: 1520629789,
    //     name: 'first last',
    //     picture: 'https://lh6.googleusercontent.com/.../photo.jpg',
    //     given_name: 'first',
    //     family_name: 'last',
    //     locale: 'en-GB'
    // }
})()
 

GoogleSignIn

Kind: global class
Export:

googleSignIn.verify(token) ⇒ Promise.<(boolean|object)>

Kind: instance method of GoogleSignIn
Returns: Promise.<(boolean|object)> - - false if id token is invalid otherwise returns account data

Param Type Description
token string google id token string

GoogleSignIn.GoogleSignIn

Kind: static class of GoogleSignIn

new GoogleSignIn(options)

Param Type Description
options object
options.clientId string google client id

@coolgk/array

a javascript / typescript module

npm install @coolgk/array

array utilities

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { toArray } from '@coolgk/array';
// OR
// const { toArray } = require('@coolgk/array');
 
const a = undefined;
const b = false;
const c = '';
const d = [1,2,3];
const e = {a:1};
 
console.log(toArray(a)); // []
console.log(toArray(b)); // [ false ]
console.log(toArray(c)); // [ '' ]
console.log(toArray(d)); // [ 1, 2, 3 ]
console.log(toArray(e)); // [ { a: 1 } ]
 

toArray(data) ⇒ array

Kind: global function

Param Type Description
data * any data to be type cast to array

@coolgk/base64

a javascript / typescript module

npm install @coolgk/base64

base64 encoded decode functions

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { encode, decode, encodeUrl, decodeUrl } from '@coolgk/base64';
// OR
// const { encode, decode, encodeUrl, decodeUrl } = require('@coolgk/base64');
 
const a = 'https://www.google.co.uk/?a=b'
const hash = encode(a);
const urlHash = encodeUrl(a);
 
console.log(a); // https://www.google.co.uk/?a=b
console.log(hash); // aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLnVrLz9hPWI=
console.log(decode(hash)); // https://www.google.co.uk/?a=b
 
console.log(urlHash); // aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLnVrLz9hPWI
console.log(decodeUrl(urlHash)); // https://www.google.co.uk/?a=b
 

Functions

encode(data)string
decode(data)string
encodeUrl(data)string
decodeUrl(data)string

encode(data) ⇒ string

Kind: global function

Param Type Description
data string string to encode

decode(data) ⇒ string

Kind: global function

Param Type Description
data string encoded hash

encodeUrl(data) ⇒ string

Kind: global function

Param Type Description
data string string to encode

decodeUrl(data) ⇒ string

Kind: global function

Param Type Description
data string base64 encoded url to decode

@coolgk/token

a javascript / typescript module

npm install @coolgk/token

an expirable, revocable, renewable token with data storage

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { Token } from '@coolgk/token';
import { createClient } from 'redis';
// OR
// const { Token } = require('@coolgk/token');
// const createClient = require('redis').createClient;
 
(async () => {
 
    const redisClient = createClient({
        host: 'localhost',
        port: 6379,
        password: '----'
    });
 
    const token = new Token({
        redisClient: redisClient,
        expiry: 5,
        token: 'abcde'
    });
 
    console.log(
        await token.verify()
    ) // false
 
    await token.renew();
 
    console.log(
        await token.verify()
    ) // true
 
    console.log(
        await token.get('var1');
    ); // null
 
    console.log(
        await token.getAll()
    ); // {}
 
    await token.set('var1', {a: 'var1', b: false});
 
    console.log(
        await token.get('var1');
    ); // {a: 'var1', b: false}
 
    await token.set('var2', 'string var 2');
 
    console.log(
        await token.getAll()
    ); // { var1: { a: 'var1', b: false }, var2: 'string var 2' }
 
    await token.delete('var2');
 
    console.log(
        await token.get('var2');
    ); // null
 
    console.log(
        await token.getAll()
    ); // { var1: { a: 'var1', b: false } }
 
    await token.destroy();
 
    console.log(
        await token.verify()
    ) // false
 
    console.log(
        await token.get('var1');
    ); // null
 
    console.log(
        await token.getAll()
    ); // {}
 
    redisClient.quit();
})()
 

Classes

Token

Constants

TokenError : object

Error Codes

Token

Kind: global class

new Token(options)

Param Type Default Description
options object
options.token string token string for creating a token object
options.redisClient object redis client from redis.createClient()
[options.prefix] string "'token'" prefix used in redis e.g. token:[TOKEN_STRING...]
[options.expiry] number 0 in seconds. 0 = never expire

token.renew([expiry]) ⇒ promise

Kind: instance method of Token

Param Type Description
[expiry] number in seconds

token.set(name, value) ⇒ promise

set a data field value

Kind: instance method of Token

Param Type Description
name string field name
value * anything can be JSON.stringify'ed

token.verify() ⇒ promise.<boolean>

verify if token has expired

Kind: instance method of Token

token.get(name) ⇒ promise

get the value of a data field

Kind: instance method of Token

Param Type Description
name string data field name

token.destroy() ⇒ promise

delete the token

Kind: instance method of Token

token.delete(name) ⇒ promise

delete a data field in the token

Kind: instance method of Token

Param Type Description
name string data field name

token.getAll() ⇒ promise.<{}>

get the values of all data fields in the token

Kind: instance method of Token

token.setToken(token)

set a new token string

Kind: instance method of Token

Param Type Description
token string new token string

TokenError : object

Error Codes

Kind: global constant
Properties

Name Type Description
INVALID_TOKEN string invalid token string
RESERVED_NAME string reserved names are used when setting token variables e.g. _timestamp
EXPIRED_TOKEN string token expired or renew() has not been called

@coolgk/url

a javascript / typescript module

npm install @coolgk/url

a simple function for parsing parameters in a url

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { getParams } from '@coolgk/url';
// OR
// const { getParams } = require('@coolgk/url');
 
const url = '/123';
const pattern = '/:id';
 
console.log(getParams(url, pattern)); // { id: '123' }
 
const url2 = '/123/abc/456';
const pattern2 = '/:id/abc/:value';
 
console.log(getParams(url2, pattern2)); // { id: '123', value: '456' }
 
const url3 = '/123/456';
const pattern3 = ':id/:value';
 
console.log(getParams(url3, pattern3)); // { id: '123', value: '456' }
 

getParams(url, pattern) ⇒ object

a simple function to get params in a url e.g. with url: user/123, pattern: user/:id returns {id: 123}

Kind: global function
Returns: object - - e.g. {userid: 123}

Param Type Description
url string url after the domain name e.g. http://abc.com/user/:id url should be /user/:id
pattern string e.g. /:userid/:name

@coolgk/unit

a javascript / typescript module

npm install @coolgk/unit

unit conversion

Report bugs here: https://github.com/coolgk/node-utils/issues

Examples

import { bytesToString, millisecondsToString } from '@coolgk/unit';
// OR
// const { bytesToString, millisecondsToString } = require('@coolgk/unit');
 
console.log(
    bytesToString(500), // 500B
    bytesToString(5000), // 4.88KB
    bytesToString(5000000), // 4.77MB
    bytesToString(5000000000), // 4.66GB
    bytesToString(5000000000000), // 4.55TB
    bytesToString(5000000000000000), // 4547.47TB
    bytesToString(5000000000000000000) // 4547473.51TB
);
 
console.log('1 sec', millisecondsToString(1 * 1000)); // 1 second
console.log('1 min', millisecondsToString(60 * 1000)); // 1 minute
console.log('100 sec', millisecondsToString(100 * 1000)); // 1 minute
console.log('3 hrs', millisecondsToString(60 * 60 * 3 * 1000)); // 3 hour
console.log('1.5 days', millisecondsToString(60 * 60 * 24 * 1.5 * 1000)); // 1 day
console.log('65 days', millisecondsToString(60 * 60 * 24 * 65 * 1000)); // 2 month
console.log('365 days', millisecondsToString(60 * 60 * 24 * 365 * 1000)); // 1 year
console.log('500 days', millisecondsToString(60 * 60 * 24 * 500 * 1000)); // 1 year
console.log('900 days', millisecondsToString(60 * 60 * 24 * 900 * 1000));// 2 year
console.log('1900 days', millisecondsToString(60 * 60 * 24 * 1900 * 1000)); // 5 year
console.log('365001 days', millisecondsToString(60 * 60 * 24 * 365001 * 1000)); // 1013 year
 

Functions

bytesToString(value)string

or use https://www.npmjs.com/package/filesize

millisecondsToString(value)string

bytesToString(value) ⇒ string

or use https://www.npmjs.com/package/filesize

Kind: global function
Returns: string - value in KB, MB, GB or TB

Param Type Description
value number value in byte

millisecondsToString(value) ⇒ string

Kind: global function
Returns: string - value in second, minute, hour, day, month or year

Param Type Description
value number number of milliseconds

install

npm i @coolgk/utils

Downloadsweekly downloads

11

version

3.1.2

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability