Utils 🔍
Utils functions and classes to any NodeJS project

The intention behind this repository is to always maintain a Utils
package with varied functions and classes to any
NodeJS project.
Installation
npm install @secjs/utils
Usage
File
Use File to create an instance of a File, it's existing or not.
import { File } from '@secjs/utils'
const existentFile = new File('path/to/existent/file.txt')
const nonExistentFile = new File('path/to/nonExistent/file.txt', Buffer.from('File content'))
existentFile.loadSync({ withContent: true })
nonExistentFile.createSync().loadSync({ withContent: true })
console.log(existentFile.createdAt)
console.log(existentFile.accessedAt)
console.log(existentFile.modifiedAt)
console.log(existentFile.fileSize)
console.log(existentFile.content)
existentFile.removeSync()
console.log(existentFile.getContentSync())
console.log(existentFile.toJSON())
console.log(existentFile.copySync('path/to/copy.txt'))
console.log(existentFile.moveSync('path/to/move.txt'))
console.log(existentFile.appendSync(Buffer.from('Content\n')))
console.log(existentFile.prependSync(Buffer.from('Content\n')))
await existentFile.load()
await existentFile.copy()
await existentFile.move()
await existentFile.remove()
await existentFile.create()
await existentFile.append()
await existentFile.prepend()
await existentFile.getContent()
await File.safeRemove(existentFile.path)
await File.isFileSync('package.json')
await File.existsSync('package.json')
await File.createFileOfSize('fake.js', 1024 * 1024 * 100)
Folder
Use Folder to create an instance of a Folder, it's existing or not.
import { Folder } from '@secjs/utils'
const existentFolder = new Folder('path/to/existent/folder')
const nonExistentFolder = new Folder('path/to/nonExistent/folder')
existentFolder.loadSync({ withSub: true, withFileContent: false })
nonExistentFolder.createSync().loadSync({ withSub: true, withFileContent: true })
console.log(existentFolder.createdAt)
console.log(existentFolder.accessedAt)
console.log(existentFolder.modifiedAt)
console.log(existentFolder.folderSize)
existentFolder.removeSync()
console.log(existentFolder.toJSON())
console.log(existentFolder.copySync('path/to/copy'))
console.log(existentFolder.moveSync('path/to/move'))
const recursive = true
console.log(existentFolder.getFilesByPattern('**/*.ts', recursive))
console.log(existentFolder.getFoldersByPattern('**', recursive))
await existentFolder.load()
await existentFolder.copy()
await existentFolder.move()
await existentFolder.remove()
await existentFolder.create()
await Folder.safeRemove(existentFile.path)
await Folder.isFolderSync('path/to/folder')
await Folder.existsSync('path/to/folder')
Is
Use Is to validate if value is from some type or is empty, is uuid, is cpf, is cep, etc...
import { Is } from '@secjs/utils'
Is.Empty('')
Is.Empty([])
Is.Empty([1])
Is.Empty({})
Is.Empty({ hello: 'world' })
Is.Empty(' ')
Is.Empty('hello')
Is.Json('not-valid-json')
Is.Ip('not-valid-ip')
Is.Uuid('not-valid-uuid')
Is.Cep('not-valid-cep')
Is.Cpf('not-valid-cpf')
Is.Cnpj('not-valid-cnpj')
Is.Async(() => {
})
Is.Async(async () => {
})
Is.Async(() => {
new Promise((resolve => resolve()))
})
Is.String('value')
Is.Undefined('value')
Is.Null('value')
Is.Boolean('value')
Is.Buffer('value')
Is.Number('value')
Is.Object('value')
Is.Date('value')
Is.Array('value')
Is.Regexp('value')
Is.Error('value')
Is.Function('value')
Is.Class('value')
Is.Integer('value')
Is.Float('value')
Is.ArrayOfObjects('')
Is.ArrayOfObjects([1, 2, 3])
Is.ArrayOfObjects([{ hello: 'world' }])
String
Use String to generate random strings, normalizations and case changes
import { String } from '@secjs/utils'
const string = 'Hello world'
const capitalize = true
String.toCamelCase(string)
String.toPascalCase(string)
String.toNoCase(string)
String.toConstantCase(string)
String.toDashCase(string)
String.toDashCase(string, capitalize)
String.toDotCase(string)
String.toDotCase(string, capitalize)
String.toSnakeCase(string)
String.toSnakeCase(string, capitalize)
String.toSentenceCase(string)
String.toSentenceCase(string, capitalize)
String.generateRandom(10)
String.generateRandomColor()
String.pluralize(string)
String.singularize(String.pluralize(string))
String.ordinalize('1')
String.ordinalize('2')
String.ordinalize('3')
String.ordinalize('10')
String.normalizeBase64('+++///===')
Exception
Use exception to extend the Error object and create custom exceptions
import { Exception } from '@secjs/utils'
const content = 'An error has ocurred in your application!'
const status = 500
const code = 'APPLICATION_ERROR'
const help = 'Delete your code and start again'
const exception = new Exception(content, status, code, help)
const withStack = true
console.log(exception.toJSON(withStack))
console.log(await exception.prettify())
Extending Exception helper
import { Exception } from '@secjs/utils'
export class InternalServerException extends Exception {
public constructor(content = 'An internal server error has ocurred', status = 500) {
super(content, status)
}
}
throw new InternalServerException()
Path
Use Path to get the absolute path from project folders.
import { Path } from '@secjs/utils'
const subPath = '/hello'
Path.pwd(subPath, beforePath)
Path.defaultBeforePath = 'build'
Path.pwd(subPath, beforePath)
Path.pwd('/src/')
Config
Handle configurations files values inside your application ecosystem
export default {
name: 'secjs'
}
export default {
host: '127.0.0.1',
port: Env('PORT', 5432),
database: Config.get('app.name')
}
Loading configuration files and get then
const config = new Config()
config.load('database.ts')
console.log(Config.get('app.name'))
console.log(Config.get('database.port'))
console.log(Config.get('database.database'))
config.load('example.ts')
config.safeLoad('app.ts')
console.log(Config.get('app.name'))
Be careful with Config.get() in configuration files ⚠️🛑
export default {
recursive: Config.get('recursive-errorB.recursive')
}
export default {
recursive: Config.get('recursive-errorA.recursive')
}
Json
Use Json to parse json without errors, deep copy, observeChanges inside objects and more.
import { Json } from '@secjs/utils'
const textWithJsons = 'string with a Json inside of it {"text":"hello"} and one more Json {"hello":"world"}'
Json.getJson(textWithJsons)
const text = 'a string that is not a valid JSON'
Json.parse(text)
const object = {
test: 'hello',
hello: () => 'hy',
}
const objectCopy = Json.copy(object)
objectCopy.test = 'hello from copy'
objectCopy.hello = () => 'hy from copy'
console.log(object.test)
console.log(object.hello())
console.log(objectCopy.test)
console.log(objectCopy.hello())
const data = {}
const doSomething = (value, args) => {
console.log(`Name changed to: ${value}`, args)
}
const args = {
value: 'args are the same second parameter of doSomething function'
}
Json.observeChanges(data, 'name', doSomething, args)
data.name = 'João'
const object = {
number1: 'good string',
number2: 'bad string',
}
const readyToSaveOnDatabase = Json.fillable(object, ['number1'])
console.log(readyToSaveOnDatabase)
const array = [1, 1, 2, 4, 4]
console.log(Json.removeDuplicated(array))
const array = ['a', 'b', 'c']
const sortedValue = Json.sort(array)
console.log(sortedValue)
Route
Use Route to manipulate paths, getParams, getQueryParams, create route matcher RegExp etc.
import { Route } from '@secjs/utils'
const absolutePath = '/tests/:id/users/:user_id'
const path = '/tests/1/users/2?page=1&limit=10'
Route.getQueryString(path)
Route.removeQueryParams(path)
Route.getQueryParamsValue(path)
Route.getQueryParamsName(path)
Route.getParamsValue(absolutePath, path)
Route.getParamsName(absolutePath)
const regExpMatcher = Route.createMatcher(absolutePath)
regExpMatcher.test(path)
regExpMatcher.test(Route.removeQueryParams(path))
Number
Use Number to manipulate numbers the best way
import { Number } from '@secjs/utils'
const arrayOfNumbers = [2, 4]
const stringNumber = "Hello my name is João, I'm 20 year old!"
console.log(Number.getLower(arrayOfNumbers))
console.log(Number.getHigher(arrayOfNumbers))
console.log(Number.extractNumber(stringNumber))
console.log(Number.extractNumbers(stringNumber))
console.log(Number.argsAverage(2, 4))
console.log(Number.arrayAverage(arrayOfNumbers))
console.log(Number.randomIntFromInterval(1, 1))
console.log(Number.randomIntFromInterval(1, 2))
console.log(Number.randomIntFromInterval(1, 2))
console.log(Number.randomIntFromInterval(1, 10))
Token
Generate U UID tokens using a prefix, and validate it to using uuidv4 lib
import { Token } from '@secjs/utils'
const uuidGeneratedToken = Token.generate('yourServicePrefix')
console.log(uuidGeneratedToken)
const isUuid = Token.verify(uuidGeneratedToken)
console.log(isUuid)
Parser
Use Parser to parse all type of data of you application
import { Parser } from '@secjs/utils'
const string1 = '1,2,3'
const separator = ','
const parsed1 = Parser.stringToArray(string1, separator)
console.log(parsed1)
Parser.arrayToString(['1', '2', '3', '4'])
Parser.arrayToString(['1', '2', '3', '4'],
{ separator: '|', lastSeparator: '-' }
)
Parser.arrayToString(['1', '2'], {
pairSeparator: '_',
})
const string2 = 'aaaasadzczaaa21313'
const parsed2 = Parser.stringToNumber(string2)
console.log(parsed2)
const object = {
joao: 'joao',
email: 'lenonsec7@gmail.com',
}
const parsed3 = Parser.jsonToFormData(object)
console.log(parsed3)
const parsed4 = Parser.formDataToJson('?joao=joao&email=lenonSec7%40gmail.com')
console.log(parsed4)
const message = 'Link: https://google.com'
console.log(Parser.linkToHref(message))
Parser.sizeToByte(1024)
Parser.sizeToByte(1048576)
Parser.sizeToByte(1073741824)
Parser.sizeToByte(1099511627776)
Parser.sizeToByte(1125899906842624)
Parser.byteToSize('1KB')
Parser.byteToSize('1MB')
Parser.byteToSize('1GB')
Parser.byteToSize('1TB')
Parser.byteToSize('1PB')
Parser.timeToMs('2 days')
Parser.timeToMs('1d')
Parser.timeToMs('10h')
Parser.timeToMs('-10h')
Parser.timeToMs('1 year')
Parser.timeToMs('-1 year')
const long = true
Parser.msToTime(172800000, long)
Parser.msToTime(86400000)
Parser.msToTime(36000000)
Parser.msToTime(-36000000)
Parser.msToTime(31557600000, long)
Parser.msToTime(-31557600000, long)
Parser.statusCodeToReason(200)
Parser.statusCodeToReason('201')
Parser.statusCodeToReason(404)
Parser.statusCodeToReason('500')
Parser.reasonToStatusCode('OK')
Parser.reasonToStatusCode('created')
Parser.reasonToStatusCode('NOT_found')
Parser.reasonToStatusCode('internal server error')
const url =
'postgresql://postgres:root@127.0.0.1:5432/postgres?paramOne=1¶mTwo=2¶mThree=3'
const connectionObject = Parser.dbUrlToConnectionObj(url)
const connectionUrl = Parser.connectionObjToDbUrl(connectionObject)
Clean
Use Clean to clean arrays and objects
import { Clean } from '@secjs/utils'
const array = [null, undefined, 1, "number"]
console.log(Clean.cleanArray(array))
const object = {
number1: "number",
number2: null,
number3: undefined,
number4: 1,
}
const object2 = {
number1: null,
number2: [object],
}
console.log(Clean.cleanObject(object))
console.log(Clean.cleanArraysInObject(object2))
Debug
Use Debug to generate debug logs in SecJS format
import { Debug } from '@secjs/utils'
const context = 'API'
const namespace = 'api:main'
const debug = new Debug(context, namespace)
// You can still change the context/namespace of the instance in runtime
debug
.buildContext(context)
.buildNamespace(namespace)
.log('Hello World!') // api:main [SecJS Debugger] - PID: 85580 - 02/15/2022, 11:47:56 AM [API] Hello World! +0ms
// You can log objects too, it will be converted to string in the formatter
debug
.buildContext('Object')
.buildNamespace('api:object')
.log({ hello: 'world' })
Made with 🖤 by jlenon7 :wave: