@mhirba/utils
is a simple way to use miscellaneous utilities
Summary
Overview
Simple package used internally at mhirba for simple utilities such as log, command line arguments parsing, etc.
Je suis adroit de la main gauche et je suis gauche de la main droite _ Raymond Devos
Installation
Use Yarn or NPM to install.
❯ yarn add @mhirba/utils
or
❯ npm install @mhirba/utils
Usage
Simple. Basic.
A tiny library with individual export functions:
mLog
Display output depending several options like colors, timestamps and newLine.
const { mLog } = require('@mhirba/utils')
mLog('Hello, World', { how: 'cyan', withTimestamps: true })
❯ node ./main.js
2019-01-04T21:55:40+01:00 :: Hello, World
mDump
Dump scalar or complex variable with typing
const { mDump } = require('@mhirba/utils')
const leet = 1337
const info = {
company: 'Mhirba',
isTech: true,
ping() {
console.log('http://mhirba.com')
}
}
mDump(leet)
mDump(info, true)
console.log('This will not be displayed')
❯ node ./main.js
~/@mhirba/utils/src/libs/mDump.js:18:
int 1337
~/@mhirba/utils/src/libs/mDump.js:18:
object (size=3) {
'company' => string "Mhirba" (length=6),
'isTech' => boolean true,
'ping' => function () {},
}
mArg
A simple wrapper of the excellent arg
package from Zeit.
The main difference is that mArg()
handle some exception and a conventional way to use help
and display the usage.
mArg()
take either 1 or 2 arguments:
- The command line specification as an object [following the
arg
package] - An optional string to display for usage
const { mArg, mLog } = require('../dist/main')
const usage = `
usage: node mArg.test.js
[--answer]
`
const args = mArg(
{
'--name': String,
'--answer': Boolean
},
usage
)
mLog(args)
if (args.answer) {
console.log('The answer is 42')
}
❯ node ./main.js --name=Majdi --answer
{ name: 'Majdi', answer: true }
The answer is 42
❯ node ./main.js --hi
Unknown or unexpected option: --hi
usage: node mArg.test.js
[--answer]
mExec
A simple function that take a shell command as argument to run it through promise.
const { mLog, mExec } = require('@mhirba/utils')
async function dumpIpConfig() {
const result = await mExec(`curl -s https://ifconfig.co/json`, {
withOutput: false
})
const networkInfo = JSON.parse(result)
const { ip } = networkInfo
mLog(`Ip address: ${ip}`, { how: 'yellow' })
await mExec(`ping ${ip}`)
}
dumpIpConfig()
❯ node ./main.js
Ip address: 90.92.250.47
⌈ `ping 90.92.250.47`
PING 90.92.250.47 (90.92.250.47): 56 data bytes
64 bytes from 90.92.250.47: icmp_seq=0 ttl=63 time=6.070 ms
64 bytes from 90.92.250.47: icmp_seq=1 ttl=63 time=2.490 ms
^[v64 bytes from 90.92.250.47: icmp_seq=2 ttl=63 time=7.225 ms
64 bytes from 90.92.250.47: icmp_seq=3 ttl=63 time=2.649 ms
^C
--- 90.92.250.47 ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 2.490/4.609/7.225/2.080 ms
⌊ the command was interrupted
Credits
Craft with