upperh

Collection of helper functions to make starting a frontend/backend JS project faster.

Usage no npm install needed!

<script type="module">
  import upperh from 'https://cdn.skypack.dev/upperh';
</script>

README

upperH

upperH is a collection of helper functions to make starting a nodeJS project faster.

Get started

Install

npm install upperh --save

How to use - Server

const H = require('upperh');


(async () => {

    // Your program here:

    var name = await H.input('What is your name?');
    var password = await H.input('Password: ', true); // input is muted (not displayed)

    await H.delay(2000); // Wait 2 seconds

    var fileContent = await H.readFile('myfile.txt');

    await H.writeFile('myfile-copy.txt', fileContent);



})();

How to use - Browser

const H = require('upperh');


H(async () => { // Will execute when DOM is loaded
    H('span.classname').removeClass('classname').closest('div').attr('data-value', 'true');
    await H.delay(1000); // Some helpers are shared between server/browser

    // Yes, you can use the same api for http requests whether it is client-side or server-side
    console.log((await H.httpGet('http://api.icndb.com/jokes/random', {}, undefined, undefined, 'form', 'json')).value.joke);

});

Classes

HObject

Collection of DOM Nodes, extends Array

Members

HBrowserHObject

H helper functions available only for Browsers. Chainable and is similar to jQuery's $ constructor.

H

H helper functions available in both Servers and browsers

HServer

H helper functions available only for Servers

HObject

Collection of DOM Nodes, extends Array

Kind: global class

h().find(selector) ⇒ HObject

Get the descendants of each element in the current set of matched elements, filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().closest(selector) ⇒ HObject

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Kind: instance method of HObject

Param Type Description
selector String | Element DOM selector or DOM element

h().contains(selector) ⇒ HObject

Checks if any of the elements in the set contains the selected element.

Kind: instance method of HObject

Param Type Description
selector String | Element DOM selector or DOM element

h().parents(selector) ⇒ HObject

Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().parent(selector) ⇒ HObject

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().children(selector) ⇒ HObject

Get the children of each element in the set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().siblings(selector) ⇒ HObject

Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().first() ⇒ HObject

Reduce the set of matched elements to the first in the set.

Kind: instance method of HObject

h().last() ⇒ HObject

Reduce the set of matched elements to the last in the set.

Kind: instance method of HObject

h().prev(selector) ⇒ HObject

Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().next(selector) ⇒ HObject

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().prevAll(selector) ⇒ HObject

Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().nextAll(selector) ⇒ HObject

Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

Kind: instance method of HObject

Param Type Description
selector String DOM selector

h().attr(name) ⇒ String

Get the value of an attribute for the first element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
name String Attribute name

h().attr(name, value) ⇒ HObject

Set an attribute for the set of matched elements.

Kind: instance method of HObject

Param Type Description
name String Attribute name
value String Attribute value

h().removeAttr(name) ⇒ HObject

Remove an attribute from each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
name String Attribute name

h().show() ⇒ HObject

Display the matched elements.

Kind: instance method of HObject

h().hide() ⇒ HObject

Hide the matched elements.

Kind: instance method of HObject

h().prop(key) ⇒ String

Get the value of a property for the first element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
key String Property name

h().prop(key, value) ⇒ HObject

Set a property for the set of matched elements.

Kind: instance method of HObject

Param Type Description
key String Property name
value String Property value

h().css(name) ⇒ String

Get the computed style properties for the first element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
name String Property name

h().css(name, value) ⇒ HObject

Set a CSS property for the set of matched elements.

Kind: instance method of HObject

Param Type Description
name String Property name
value String Property value

h().css(properties) ⇒ HObject

Set one or more CSS properties for the set of matched elements.

Kind: instance method of HObject

Param Type Description
properties Object Key-value pair of properties to set.

h().append(content) ⇒ HObject

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
content Mixed Content to insert. (either a selector, HTML content or a DOM Node)

h().appendTo(target) ⇒ HObject

Insert every element in the set of matched elements to the end of the target(s).

Kind: instance method of HObject

Param Type Description
target Mixed Target of the content. (either a selector, HTML content or a DOM Node)

h().prepend(content) ⇒ HObject

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
content Mixed Content to insert. (either a selector, HTML content or a DOM Node)

h().prependTo(target) ⇒ HObject

Insert every element in the set of matched elements to the beginning of the target(s).

Kind: instance method of HObject

Param Type Description
target Mixed Target of the content. (either a selector, HTML content or a DOM Node)

h().insertBefore(target) ⇒ HObject

Insert every element in the set of matched elements before the target.

Kind: instance method of HObject

Param Type Description
target String DOM selector

h().before(content) ⇒ HObject

Insert content, specified by the parameter, before each element in the set of matched elements

Kind: instance method of HObject

Param Type Description
content String HTML code or DOM selector

h().insertAfter(target) ⇒ HObject

Insert every element in the set of matched elements after the target.

Kind: instance method of HObject

Param Type Description
target String DOM selector

h().after(content) ⇒ HObject

Insert content, specified by the parameter, after each element in the set of matched elements

Kind: instance method of HObject

Param Type Description
content String HTML code or DOM selector

h().wrap(element) ⇒ HObject

Wrap an HTML structure around each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
element String Wrapping element.

h().wrapInner(element) ⇒ HObject

Wrap an HTML structure around the content of each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
element String Wrapping element.

h().empty() ⇒ HObject

Remove all child nodes of the set of matched elements from the DOM.

Kind: instance method of HObject

h().remove() ⇒ void

Remove the set of matched elements from the DOM.

Kind: instance method of HObject

h().eq(index) ⇒ HObject

Reduce the set of matched elements to the one at the specified index.

Kind: instance method of HObject

Param Type Description
index Number Index of the element

h().index() ⇒ Number

Search for a given element from among the matched elements.

Kind: instance method of HObject

h().html() ⇒ String

Get the HTML contents of the first element in the set of matched elements.

Kind: instance method of HObject

h().html(content) ⇒ HObject

Set the HTML contents of each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
content String HTML content

h().text() ⇒ String

Get the combined text contents of each element in the set of matched elements, including their descendants.

Kind: instance method of HObject

h().text(content) ⇒ HObject

Set the content of each element in the set of matched elements to the specified text.

Kind: instance method of HObject

Param Type Description
content String Text content

h().val() ⇒ String

Get the current value of the first element in the set of matched elements.

Kind: instance method of HObject

h().val(value) ⇒ HObject

Set the value of each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
value String Value

h().each(function) ⇒ HObject

Iterate over a jQuery object, executing a function for each matched element.

Kind: instance method of HObject

Param Type Description
function function Function to execute

h().get() ⇒ Node

Retrieve the elements matched as a vanilla Array.

Kind: instance method of HObject

h().get(index) ⇒ Node

Retrieve one of the elements matched.

Kind: instance method of HObject

Param Type Description
index Number Index of the element to return

h().addClass(className) ⇒ HObject

Adds the specified class(es) to each element in the set of matched elements

Kind: instance method of HObject

Param Type Description
className String Class name

h().removeClass(className) ⇒ HObject

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

Kind: instance method of HObject

Param Type Description
className String Class name

h().toggleClass(className) ⇒ HObject

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

Kind: instance method of HObject

Param Type Description
className String Class name

h().hasClass(className) ⇒ Boolean

Determine whether any of the matched elements are assigned the given class.

Kind: instance method of HObject

Param Type Description
className String Class name

h().filter(selector) ⇒ HObject

Reduce the set of matched elements to those that match the selector.

Kind: instance method of HObject

Param Type Description
selector String DOM Selector

h().filter(fn) ⇒ HObject

Reduce the set of matched elements to those that match the function's test.

Kind: instance method of HObject

Param Type Description
fn function Function used as a test for each elkement in the set.

h().is(selector) ⇒ Boolean

Check the current matched set of elements against a selector and return true if at least one of these elements matches the given arguments.

Kind: instance method of HObject

Param Type Description
selector String DOM Selector

h().offset() ⇒ Object

Get the current coordinates of the first element in the set of matched elements, relative to the document.

Kind: instance method of HObject
Returns: Object - {top, left}

h().on(events, selector, callback, options) ⇒ HObject

Attach an event handler function for one or more events to the selected elements.

Kind: instance method of HObject

Param Type Description
events String One or more space-separated event types and optional namespaces.
selector String A selector string to filter the descendants of the selected elements that trigger the event.
callback function Event Handler
options Object Additional options for .addEventListener

h().one(events, selector, callback, options) ⇒ HObject

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Kind: instance method of HObject

Param Type Description
events String One or more space-separated event types and optional namespaces.
selector String A selector string to filter the descendants of the selected elements that trigger the event.
callback function Event Handler
options Object Additional options for .addEventListener

h().off(events, callback) ⇒ HObject

Remove an event handler.

Kind: instance method of HObject

Param Type Description
events String One or more space-separated event types and optional namespaces.
callback function Event Handler

h().trigger(event, extraParams, eventOptions) ⇒ HObject

Execute all handlers and behaviors attached to the matched elements for the given event type.

Kind: instance method of HObject

Param Type Description
event String Event types and optional namespaces.
extraParams Array.<Mixed> Additional parameters to pass along to the event handler.
eventOptions Object Additional event options for CustomEvent (e.g. for controlling if event bubbles...)

h().triggerHandler(event, extraParams, eventOptions) ⇒ Mixed

Execute all handlers attached to an element for an event.

Kind: instance method of HObject

Param Type Description
event String Event types and optional namespaces.
extraParams Array.<Mixed> Additional parameters to pass along to the event handler.
eventOptions Object Additional event options for CustomEvent (e.g. for controlling if event bubbles...)

HBrowser ⇒ HObject

H helper functions available only for Browsers. Chainable and is similar to jQuery's $ constructor.

Kind: global variable

Param Type Description
parameter String | function DOM selector, HTML code that will be used to create new elements, Function to run when document is ready. Similar to $(function(){ }) or $(document).ready(function(){ })

H

H helper functions available in both Servers and browsers

Kind: global variable

H.isArray ⇒ Boolean

Checks if variable is an array (equivalent to Array.isArray)

Kind: static property of H

Param Type Description
variable Mixed Variable to check

H.regexp

Helper regular expressions (RegExp) handle : Valid handle (lowercase letters, numbers, underscores and dashes). email : Valid email address

Kind: static property of H

H.Error

Custom Error constructor

Kind: static property of H

Param Type Description
message String Error message
code Number Error code.

H.loadScript(url, [reload]) ⇒ Promise

Loads a JS script

Kind: static method of H
Returns: Promise - Resolves when script is loaded

Param Type Default Description
url String JS script url
[reload] Boolean false If set to true, the scrippt will be appended regardless if it was previously loaded or not

H.loadStylesheet(url, [reload]) ⇒ Promise

Loads a CSS stylesheet

Kind: static method of H
Returns: Promise - Resolves when stylesheet is loaded

Param Type Default Description
url String CSS stylesheet url
[reload] Boolean false If set to true, the stylesheet will be reloaded regardless if it was previously loaded or not

H.isObject(variable) ⇒ Boolean

Checks if variable is an object and not an array

Kind: static method of H

Param Type Description
variable Mixed Variable to check

H.delay(time) ⇒ Promise

Wait for a number of miliseconds

Kind: static method of H

Param Type Description
time Number Time in miliseconds

H.timestampMs() ⇒ Number

Returns current timestamp in miliseconds

Kind: static method of H
Returns: Number - timestamp in miliseconds

H.timestamp() ⇒ Number

Returns current timestamp in seconds

Kind: static method of H
Returns: Number - timestamp in seconds

H.relativeTime(timestamp) ⇒ String

Converts a timestamp into relative time. E.g. about 2 hours ago; less than a minute; in about 5 minutes

Kind: static method of H
Returns: String - relative representation of timestamp

Param Type Description
timestamp Number | Date Time

H.handlize(str) ⇒ String

Converts a string into a handlized format (uppercase letters, numbers and dashes)

Kind: static method of H
Returns: String - Handle

Param Type Description
str String String to handlize

H.regexpEscape()

Escapes a regular expression string (RegExp) s : String to escape

Kind: static method of H

H.hasOwnProp(obj, key) ⇒ Bool

Determines if an object has a property. (uses Object.prototype for security)

Kind: static method of H
Returns: Bool - True if obj has the key property

Param Type Description
obj Object Object to check
key String Property to check

H.getVariable(obj, path) ⇒ Mixed

Goes through an object and returns value of a specific path (using dot notation)

Kind: static method of H
Returns: Mixed - Value of the path element

Param Type Description
obj Object Input object
path String Path to traverse (dot notation). e.g. parent.children.property

H.setVariable(obj, path, value)

Goes through an object and sets the value of a specific path (using dot notation)

Kind: static method of H

Param Type Description
obj Object Input object
path String Path to traverse (dot notation). e.g. parent.children.property
value Mixed New value to inject

H.escape(str) ⇒ String

Escapes a string for HTML injection

Kind: static method of H
Returns: String - Cleaned output

Param Type Description
str String Input string

H.httpRequest(method, url, payload, headers, extras, [inFormat], [outFormat]) ⇒ Promise.<String>

Requests an HTTP endpoint

Kind: static method of H
Returns: Promise.<String> - Response body

Param Type Default Description
method String Method to use (GET
url String HTTP endpoint
payload Object Payload to inject (will be converted to query string in case of GET request otherwise, the payload is sent as a JSON body)
headers Object Headers to inject
extras Object extra options for the request (same as fetch API options)
[inFormat] String "json" Format of the input request (json, form).
[outFormat] String "json" Format of the output response (json, text, buffer, stream).

H.httpGet(url, payload, headers, extras, [inFormat], [outFormat]) ⇒ Promise.<String>

Requests a GET HTTP endpoint

Kind: static method of H
Returns: Promise.<String> - Response body

Param Type Default Description
url String HTTP endpoint
payload Object Payload to inject will be converted to query string
headers Object Headers to inject
extras Object extra options for request (same as fetch API options)
[inFormat] String "json" Format of the input request (json, form).
[outFormat] String "json" Format of the output response (json, text, buffer, stream).

H.httpPost(url, payload, headers, extras, [inFormat], [outFormat]) ⇒ Promise.<String>

Requests a POST HTTP endpoint

Kind: static method of H
Returns: Promise.<String> - Response body

Param Type Default Description
url String HTTP endpoint
payload Object Payload to inject
headers Object Headers to inject
extras Object extra options for request (same as fetch API options)
[inFormat] String "json" Format of the input request (json, form).
[outFormat] String "json" Format of the output response (json, text, buffer, stream).

H.httpPut(url, payload, headers, extras, [inFormat], [outFormat]) ⇒ Promise.<String>

Requests a PUT HTTP endpoint

Kind: static method of H
Returns: Promise.<String> - Response body

Param Type Default Description
url String HTTP endpoint
payload Object Payload to inject
headers Object Headers to inject
extras Object extra options for request (same as fetch API options)
[inFormat] String "json" Format of the input request (json, form).
[outFormat] String "json" Format of the output response (json, text, buffer, stream).

H.httpDelete(url, payload, headers, extras, [inFormat], [outFormat]) ⇒ Promise.<String>

Requests a DELETE HTTP endpoint

Kind: static method of H
Returns: Promise.<String> - Response body

Param Type Default Description
url String HTTP endpoint
payload Object Payload to inject
headers Object Headers to inject
extras Object extra options for request (same as fetch API options)
[inFormat] String "json" Format of the input request (json, form).
[outFormat] String "json" Format of the output response (json, text, buffer, stream).

HServer

H helper functions available only for Servers

Kind: global variable

H.readFileBuff ⇒ Promise.<Buffer>

Reads a local file and returns a buffer

Kind: static property of HServer
Returns: Promise.<Buffer> - Content of the file as a buffer

Param Type Description
path String File path

H.readFile ⇒ Promise.<String>

Reads a local file and returns it content as a string

Kind: static property of HServer
Returns: Promise.<String> - Content of the file's content as a string

Param Type Description
path String File path

H.readDir ⇒ Promise.<Array>

Returns the list of files of a directory

Kind: static property of HServer
Returns: Promise.<Array> - Directory list

Param Type Description
path String Path of the directory

H.mkdir ⇒ Promise

Creates a directory

Kind: static property of HServer

Param Type Description
path String Path of the directory

H.writeFile ⇒ Promise

Writes a string into a file

Kind: static property of HServer

Param Type Description
path String File path
content String New file content

H.readFileSync ⇒ String

Reads a local file (synchronously) and returns it content as a string

Kind: static property of HServer
Returns: String - Content of the file's content as a string

Param Type Description
path String File path

H.writeFileSync

Writes a string into a file (synchronously)

Kind: static property of HServer

Param Type Description
path String File path
content String New file content

H.exec ⇒ Promise.<stdout, stderr>

Executes a child process

Kind: static property of HServer
Returns: Promise.<stdout, stderr> - Returns command output (stdout & stderr)

Param Type Description
command String Command to execute
[options] Object Options (see child_process.exec)

H.uniqueToken ⇒ String

Returns a random unique token

Kind: static property of HServer
Returns: String - Hexadecimal representation of token

H.md5 ⇒ String

Returns MD5 hash

Kind: static property of HServer
Returns: String - MD5 hash of input (in HEX format)

Param Type Description
str String | Buffer Input to get hash of

H.sha1 ⇒ String

Returns SHA1 hash

Kind: static property of HServer
Returns: String - SHA1 hash of input (in HEX format)

Param Type Description
str String | Buffer Input to get hash of

H.sha256 ⇒ String

Returns SHA256 hash

Kind: static property of HServer
Returns: String - SHA256 hash of input (in HEX format)

Param Type Description
str String | Buffer Input to get hash of

H.encrypt ⇒ String | Buffer

Encrypts an input string with aes-256-cbc encryption algorithm

Kind: static property of HServer
Returns: String | Buffer - Encrypted data

Param Type Default Description
data String | Buffer Input data to encrypt
key String Encryption key in HEX format. Must be a 32byte key for a 256bit algorithm.
iv String IV to use for the encryption in HEX format. For AES, length must be 16
[algo] String "aes-256-cbc" Encryption algorithm
[format] String "hex" Format of output

Example

const key = crypto.scryptSync('Password here', 'salt', 32).toString('hex'); // 32 = 256/8
const iv = Buffer.from('d65a8b0dcbde0b76cc746faaf0b0beaa', 'hex'); // For AES, length is 16
var encryptedData = H.encrypt('My secret data', key, iv);

H.decrypt ⇒ String | Buffer

Decrypts an input string with aes-256-cbc encryption algorithm

Kind: static property of HServer
Returns: String | Buffer - Encrypted data

Param Type Default Description
data String | Buffer Input data to decrypt
key String Decryption key in HEX format. Must be a 32byte key for a 256bit algorithm.
iv String IV to use for the decryption in HEX format. For AES, length must be 16
[algo] String "aes-256-cbc" Decryption algorithm
[format] String "hex" Format of output

Example

const key = crypto.scryptSync('Password here', 'salt', 32).toString('hex'); // 32 = 256/8
const iv = Buffer.from('d65a8b0dcbde0b76cc746faaf0b0beaa', 'hex'); // For AES, length is 16
var originalData = H.encrypt(encryptedData, key, iv);

H.render ⇒ Promise.<String>

Renders a nunjucks/jinja template string asynchronously

Kind: static property of HServer
Returns: Promise.<String> - Rendered template

Param Type Description
str String Template string (jinja/nunjucks)
data Object Data to inject in template
filters Object Filters functions to allow in template
includeCb function Callback function that is called whenever the template calls the include instruction.

H.renderFile ⇒ Promise.<String>

Renders a nunjucks/jinja template file asynchronously

Kind: static property of HServer
Returns: Promise.<String> - Rendered template

Param Type Description
str String Path of template file to render
data Object Data to inject in template
filters Object Filters functions to allow in template
includeCb function Callback function that is called whenever the template calls the include instruction.

H.input ⇒ Promise.<String>

Requests input from user in command line interface

Kind: static property of HServer
Returns: Promise.<String> - the value the user has entered

Param Type Default Description
q String Question to ask to user during input
[muted] Boolean false Whether to mute the user input (for passwords)

H.waitForKey ⇒ String

Shortcut for H.input but without the muted parameter set to true

Kind: static property of HServer
Returns: String - the value the user has entered

Param Type Description
q String Question to ask to user during input

H.onKeypress

Listens to keypresses and calls callback when a key is pressed. Exists when Ctrl+C is typed

Kind: static property of HServer

Param Type Description
cb function Callback to function that will listen to key presses

H.httpServer

Starts an HTTP server and calls specific handlers depending on request url

Kind: static property of HServer

Param Type Default Description
[post] Number 80 Post to listen to
handlers function | Object If function, it will run function and use returned Object to select handler. If Object, it will use it directly to select the handler. The handler is selected if it matches the request url. If the handler's key starts with ^, it will be considered as a REGEX.
options Object Extra options. defaultHandler, onError, beforeHandler, pathFlags, afterHandler, autoEnd, maxPostRequestSize,