项目作者: LostAbaddon

项目描述 :
My JS core lib
高级语言: JavaScript
项目地址: git://github.com/LostAbaddon/jLAss.git
创建时间: 2018-11-02T03:56:36Z
项目社区:https://github.com/LostAbaddon/jLAss

开源协议:GNU General Public License v3.0

下载


jLAss

  • Version: 1.0.3
  • Author: LostAbaddon
  • NodeJS Version: >= 14.0.0

My Personal Javascript Core Lib

Install

  1. npm install https://github.com/LostAbaddon/jLAss.git --save

Includes

  • 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

Extends

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

Global

  • 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 ~/

Promisify

  • 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.
    1. promisify(fn(..., res)).timeout([timeout], [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, callback)
    • promisify.serial([fn1, fn2, ..., fnx], data, callbak)
  • 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, callback)
    • 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

  • object.copy
  • object.extent
  • object.isSubClassOf

Function

  • Function.is
  • AsyncFunction

    Class of async functions
  • AsyncFunction.is

Array

  • 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

  • string.prepadding
  • String.random
  • String.blank
  • String.is

Symbol

  • Symbol.setSymbols
  • Symbol.is

Math

  • 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.

Proxy

  • Proxy.toObject
    Convert Proxy delegator to a normal object.

Events [TBD]

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

CommandLine

CLI utils, includes cl parse and interface.

CommandLine Parser

Demo:

  1. var cmdLauncher = clp({
  2. title: SyncerTitle + ' v' + SyncerVersion,
  3. mode: 'process'
  4. })
  5. .describe('多文件夹自动同步者。\n' + setStyle('当前版本:', 'bold') + 'v' + SyncerVersion)
  6. .addOption('--config -c <config> >> 配置文档地址')
  7. .addOption('--socket -skt >> 启用Socket后台模式' + setStyle('【待开发】', ['green', 'bold']))
  8. .on('command', params => {
  9. ...
  10. rtmLauncher.launch();
  11. })
  12. .on('done', async params => {
  13. ...
  14. })
  15. ;
  16. var rtmLauncher = clp({
  17. title: SyncerTitle + ' v' + SyncerVersion,
  18. mode: 'cli',
  19. hint: {
  20. welcome: setStyle('欢迎来到同步空间~', 'yellow underline bold'),
  21. byebye: setStyle('世界,终结了。。。', 'magenta bold')
  22. },
  23. historyStorage: {
  24. limit: 100
  25. }
  26. })
  27. .describe('多文件夹自动同步者。\n' + setStyle('当前版本:', 'bold') + 'v' + SyncerVersion)
  28. .add('list|lt >> 显示当前分组同步信息')
  29. .addOption('--group -g <group> >> 指定group标签后可查看指定分组下的源情况')
  30. .addOption('--files -f <path> >> 查看指定路径下的文件列表')
  31. .addOption('--all -a >> 显示所有文件与文件夹,不打开则只显示有变化的文件与文件夹')
  32. .on('command', (param, command) => {
  33. ...
  34. })
  35. .on('done', async params => {
  36. ...
  37. })
  38. .on('quit', (param, command) => {
  39. ...
  40. })
  41. .on('exit', (param, command) => {
  42. ...
  43. })
  44. .on('list', (param, all, command) => {
  45. ...
  46. })
  47. ;
  48. cmdLauncher.launch();

Threads

  • 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;
  • ThreadWorker.Stat

    Status of worker: IDLE, BUSY, DEAD
  • ThreadWorker

    A worker with basic core libs.
    • Use register(tag, fn) to response the request from main thread;

      register the “init” event to response the init_data which passed from main thread.
    • Use send(msg) to send message to main thread;
    • Use request(event, data) to call main thread with message { event, data};
    • Use suicide to tell main thread to kill current thread worker
  • 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 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 create or the given files;
  • ThreadPool.killAll()

    Kill all the threads and release the pool.

Datastore and Cache

  • LRUCache & LRUCache.withDatastore

    Latest Recently Use Cache
  • UFCache & UFCache.withDatastore

    Usage Frequency Cache

Utils

  • ModuleManager

    use “global._” to load and set namespace.
  • Utils.getHealth

    CPU and Memory usage utils.
  • logger

    Generate a colored logger.

FS Utils

  • 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
  • FS.hasFile
  • FS.getFolderMap
  • Utils.preparePath

    Check path and create necessary folders.
  • Utils.preparePathSync

    Sync version of Utils.preparePath.