Personal Javascript Core Lib, includes thread manager; promisify, once, pump and stack function; fs utils; Object, Array, Function, Class, String, Symbol and Time extends; CLI and CLP; and some useful utils and tools.
npm install jlassMy Personal Javascript Core Lib
> Author: LostAbaddon
> Version: 0.1.5
> NodeJS Version: >= 10.0.0
- Module Manager for b/n
- Extends for Class, Object, Function, Promise, Date and Time, Symbol
- Log Utils
- System Monitor Utils
- FileSystem Utils
- Datastore and Cache
- Math(TBD)
- Threads
- Sync and Async Events
- CommandLine Tools
- Other Utils
We can use "global" in both browser and node (b/n)
> UpCase for class, LowCase for instance
> Obj.Y for function, Obj:Y for property
- promisify
- oncilize
Make function and promise run only once.
call fn.refresh() to allow it be run again.
- pumplize
Make function delay for a while and use the last called arguments (stack mode) or all the called arguments (pump mode).
Default mode is stack mode.
- setImmediate
Fire callback when the next loop just begins.
- nextTick
Fire callback when current loop just ends.
- wait
Promisify version for setTimeout
- waitLoop
Promisify version for setImmediate
- waitTick
Promisify version for nextTick
- waitQueue
Promisify version for queueMicrotask
which is a V8 version of nextTick and always run after nextTick.
- Clock
Event-Timestamp Manager
- loadall
load all js / json files under a given folder, and the second argument can decide load the sub folders or not, which default value is true.
- Version
Version class for parsing version strings.
- getLoadPath
Parse filepath to a loadable path.
If start with ./ then the root path is jLass path; if start with ~/ then the root path will be process.cwd().
- setLoadRoot
Change the default root path for ~/
- global.promisify
Convert a function to a Promise object.
The last argument of the function is "next" which is the resolve function of Promise.
- global.promisify.withTimeout
Convert a function to a Promise object with timeout.
The returned Promise object has a function timeout which can set timeout or callback or both.
Timeout <= 0 means never timeout.
``javascript`
promisify(fn(..., res)).timeout([timeout], [callback]);promisify.serial(fn1, fn2, ..., fnx, data, callback)
- global.promisify.serial
Do the tasks one by one, and the result of previous one will be passed to the next one.
Alias: promisify.s
Two usages:
- promisify.serial([fn1, fn2, ..., fnx], data, callbak)
- promisify.parallel(fn1, fn2, ..., fnx, data, callback)
- global.promisify.parallel
Do the tasks simulately, and the results will be arranged in an array, and passed to the callback.
Alias: promisify.p
Two usages:
- promisify.parallel([fn1, fn2, ..., fnx], data, callbak)
-
- global.promisify.any
Do the tasks simulately, and only returns the first finished one.
Alias: promisify.a
Two usages:
- promisify.any(fn1, fn2, ..., fnx, data, callback)promisify.any([fn1, fn2, ..., fnx], data, callbak)
-
- object.copy
- object.extent
- object.isSubClassOf
- Function.is
- AsyncFunction
Class of async functions
- AsyncFunction.is
- array.copy
- array.randomize
- array.remove
- array.translate
- array.has
- array.query
- array:first
- array:last
- Array.is
- Array.generate
- Array.random
- uint8Array.copy
- string.prepadding
- String.random
- String.blank
- String.is
- Symbol.setSymbols
- Symbol.is
- Math.pick
For Array, pick one random element inside it.
For Number, pick a boolean value whether a random number less than the given value;
- Math.range
Pick a random number in a range.
Some utils for event-related functions.
- FiniteStateMachine
- EventManager for both sync and async callbacks
- Broadcast
- Event Pipe with and without Barrier
- Channel
- Tunnel: Thread-crossing Channel
CLI utils, includes cl parse and interface.
Demo:
`javascript
var cmdLauncher = clp({
title: SyncerTitle + ' v' + SyncerVersion,
mode: 'process'
})
.describe('多文件夹自动同步者。\n' + setStyle('当前版本:', 'bold') + 'v' + SyncerVersion)
.addOption('--config -c
.addOption('--socket -skt >> 启用Socket后台模式' + setStyle('【待开发】', ['green', 'bold']))
.on('command', params => {
...
rtmLauncher.launch();
})
.on('done', async params => {
...
})
;
var rtmLauncher = clp({
title: SyncerTitle + ' v' + SyncerVersion,
mode: 'cli',
hint: {
welcome: setStyle('欢迎来到同步空间~', 'yellow underline bold'),
byebye: setStyle('世界,终结了。。。', 'magenta bold')
},
historyStorage: {
limit: 100
}
})
.describe('多文件夹自动同步者。\n' + setStyle('当前版本:', 'bold') + 'v' + SyncerVersion)
.add('list|lt >> 显示当前分组同步信息')
.addOption('--group -g
.addOption('--files -f
.addOption('--all -a >> 显示所有文件与文件夹,不打开则只显示有变化的文件与文件夹')
.on('command', (param, command) => {
...
})
.on('done', async params => {
...
})
.on('quit', (param, command) => {
...
})
.on('exit', (param, command) => {
...
})
.on('list', (param, all, command) => {
...
})
;
cmdLauncher.launch();
`
- Utils.Threads
Simple Thread Manager, return a thread-worker wrapper.
Worker will load a list of js core lib.
- Utils.Threads.create(filelist, init_data)
Create a thread and load filelist, start with init_data
- Utils.Threads.evaluate(fun, data)
Create a thread and run the given function with given data.
- Worker
Wrapped ThreadWorker.
- worker.send(msg) to send message to thread;worker.load(files)
- to load files;worker.request(msg, data)
- to call thread worker with message { event, data }, return a promise object;worker.evaluate(fun, data)
- to call thread worker to run the given function with given data;worker.suicide()
- to kill the thread worker;count
- is the running task count;IDLE
- ThreadWorker.Stat
Status of worker: , BUSY, DEADregister(tag, fn)
- ThreadWorker
A worker with basic core libs.
- Use to response the request from main thread;send(msg)
register the "init" event to response the init_data which passed from main thread.
- Use to send message to main thread;request(event, data)
- Use to call main thread with message { event, data};suicide
- Use to tell main thread to kill current thread workercreate
- ThreadPool
A thread pool which can choise thread automatically.
- ThreadPool.create(size, files, data)
Create a batch of threads with init files and data.
- ThreadPool.load(files)
Make all threads load files.
- ThreadPool.request(event, data, cb)
Choose a free thread or a thread with least tasks to run the given event;
- ThreadPool.requestAll(event, data, cb)
Make all thread to do the job.
- ThreadPool.evaluate(fun, data, cb)
Choose a free thread or a thread with least tasks to do the evaluation;
- ThreadPool.refresh([files])
Kill the free threads and reload it, with the files set in or the given files;create` or the given files;
- ThreadPool.refreshAll([files])
Kill the free threads, and when the busy threads finish all their jobs then suicide, and reload all the threads with the files set in
- ThreadPool.killAll()
Kill all the threads and release the pool.
- LRUCache & LRUCache.withDatastore
Latest Recently Use Cache
- UFCache & UFCache.withDatastore
Usage Frequency Cache
- ModuleManager
use "global._" to load and set namespace.
- Utils.getHealth
CPU and Memory usage utils.
- logger
Generate a colored logger.
- FS.mkfolder
Create nonexist folder automatically.
- FS.filterPath
Filter the filss and folders and others.
- FS.createFolders
Create list of folders.
- FS.createEmptyFiles
- FS.deleteFiles
Delete list of files.
- FS.deleteFolders
Delete list of folders.
- FS.watchFolderAndFile
- Utils.preparePath
Check path and create necessary folders.
- Utils.preparePathSync
Sync version of Utils.preparePath.