1.1.6 • Published 3 years ago

dslog v1.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

How To Start

Start a new node project and install typescrit and dslog.

  npm init
  npm i --save-dev typescript tslib @types/node
  npm i --save dslog

In your typescript config file set the types to be.

{
    "types": ["node", "tslib", "dslog"]
}

And then you can simply require the dslog object and define it as DSLogger.

See the code bellow to get started quickly.

Starter Code

const dsLog: DSLogger = require("dslog");
(async () => {
    dsLog
        //Define the program
        .defineSplashScreen(() => {
            dsLog
                .newScreen()
                .show(dsLog.getString("star"), "Raw")
                .logProgramTitle()
                .sleep(500);
        })
        .defineProgramTitle("[ DS TESTING ]")
        .defineHelpText("This is an easy command line tool.")
        //Add command line args
        .addParam({
            flag: "a",
            name: "auto",
            desc: "Auto parse",
            type: "boolean",
            required: false,
            valueNeeded: true,
        })
        .addParam({
            flag: "b",
            name: "batch",
            desc: "Auto batch",
            type: "string",
            required: false,
            valueNeeded: true,
        })
        .addParam({
            flag: "c",
            name: "cache",
            desc: "Auto cache",
            type: "number",
            required: false,
            valueNeeded: false,
        })
        .newScreen();
    //Get command line args
    (await dsLog.initProgramInput())
        //Check if they are set
        .ifParamIsset("a", (value: any, args: any) => {
            dsLog.showSleep(value, "Info");
        })
        .ifParamIsset("b", (value: any, args: any) => {
            dsLog.showSleep(value, "Info");
        })
        .ifParamIsset("c", (value: any, args: any) => {
            dsLog.showSleep(value, "Info");
        })
        .newScreen()
        .RAW.show(dsLog.getParam("a"))
        .show(dsLog.getParam("b"))
        .show(dsLog.getParam("c"))
        .sleep(1000)
        //Start a new screen
        .splashScreen()
        .BLINK.showSleep("BLINK")
        .INFO.showSleep("Some Info.")
        .GOOD.showSleep("Everything is fine.")
        .ERROR.showSleep("Everything is not fine.")
        .WARNING.showSleep("Something may be wrong.")
        .CLEAR.newScreen()
        //Add a progress and service bar
        .newProgressBar("test");
    await dsLog.incrementProgressBar("test", 100);
    dsLog.newServiceBar("test");
    (await dsLog.asyncSleep(3000))
        .destroyServiceBar("test")
        .newScreen()
        .showSleep("All good.", "Raw")
        .newScreen()
        //Get users input
        .show("Starting user input", "Info")
        .ask("enter name", "name", "string")
        .ask("enter num", "num", "number");
    (await dsLog.startPrompt())
        .showSleep(dsLog.getInput("name"), "Info")
        .restartPrompt()
        .ask("enter email", "email", "email")
        .ask("enter password", "pass", "password")
        .fail(true, "Password is not correct.", 3, () => {
            process.exit(0);
        })
        .ask("enter comment", "comment", "string");
    (await dsLog.startPrompt()).showSleep(dsLog.getInput("comment"), "Info");
})();

Documentation

Table Of Contents

If you use this as a node module it will auto require "readline" which is built into node.

If you need to access readline later you can grab it from the dslog object.

Program Params

Functions related to getting command line input for the program.

dsLog
    .addParam({
        flag: "a",
        name: "auto",
        desc: "Auto parse",
        type: "string[]",
        required: false,
        valueNeeded: true,
    })
    .addParam({
        flag: "b",
        name: "batch",
        desc: "Batch parse",
        type: "boolean",
        required: false,
        valueNeeded: true,
    });
(await dsLog.initProgramInput())
    .ifParamIsset("a", (value: any, args: any) => {
        dsLog.logSleep(value);
    })
    .ifParamIsset("b", (value: any, args: any) => {
        dsLog.logSleep(value);
    })
    .logSleep(dsLog.getParam("b"));

Param Types

TypeDescription
stringJust chars.
string[]Just an arrary of strings with just chars.
stringallA string of chars and numbers.
stringall[]A string array of chars and numbers.
numberJust numbers.
number[]Just an arrary of numbers.
booleanCan be left blank for true or user can input "true"/"false"
boolean[]An array of booleans.

Param Object

TypeDescription
flagFlag for cli to look for. Must be a single char. It looks for your flag with "-" appended.
nameName for cli to look for. Must be a single char. It looks for your flag with "--" appended.
descDescription used for help screen.
typeThe type of param. Must be ParamType.
requiredDefault is false. If set to true the program will show an error if this param is not set.
valueNeededDefault is false. If set to true the user must enter a value for a flag if used. Otherwise the param is set to a blank string for numbers. For boolean it is auto set to true. And finally for numbers it will default to 0.

Functions

FunctionParamsReturnsDescription
addParamparam : ParamObjectselfAdds a param to the program.
getInitalProgramArgsnonestring[]Get the params passed to the program before the start of the flags. For instance "node index.js -a" would return 'index.js'.
getParamgetParam : stringselfGet a user's input for a param.
ifParamIssetparam : string, func : (value:any,args:any)=>{} ,args : anyselfIf a param is set, run a function that will be passed the value and any args you give as the arg object.
initProgramInputnonePromise of selfParse the user's input. Must be called in order for the param functions to work.

Show and Log Functions

Functions related to logging to the console.

dsLog
    .defineSleepTime(300)
    .INFO.logSleep(["Info 1", "Info 2", { cool: "This is cool" }])
    .WARNING.logSleep(["Warning 1", "Warning 2"])
    .RAW.logTable({ someData: ["1", "2", "4"] })
    .GOOD.defineSleepTime(100)
    .logSleep(["It", "is", "all", "good"]).CLEAR;

Message Types

TypeDescription
InfoMessage with blue background and white text.
GoodMessage with green background and white text.
WarningMessage with yellow background and white text.
ErrorMessage with red background and white text.
TitleMessage with purple background.
RawMessage with no styling.
DataMessage sent as JSON object. Will be converted to string and shown without styling.
BlinkMessage with blink style.

Functions

Show vs Log

Log functions just log the message without setting the console cursor. While show functions set the cursor then show the message. This can be usefull to show content at a specific row. Thoe normal log functions will work just for basic program outoput. Also, please note before using the show function it is best to clear the screen. And the progress bar and service bar use show functions not log functions right now. This is so you can have multiple of them and keep track of them.

FunctionParamsReturnsDescription
newScreennoneselfClears the screen and resets the console log row.
showmessage : string or number or object or any[], type ?: MessageType or "none"selfLogs message at current row.
showSleepmessage : string or number or object or any[], type ?: MessageType or "none" , ms ?: numberselfLogs message at current sleep row then sync sleep for given miliseconds.
showAtmessage : string or number or object or any[], params : {row ?: number,type : MessageType or "none", , col ?: number }selfLogs message at given row.
showAtSleepmessage : string or number or object or any[], params : {row ?: number, type ?: MessageType or "none",sleep ?: number, col ?: number }selfLogs message at given row and sleeps.
logmessage : string or number or object or any[], type ?: MessageType or "none"selfLog message without adjusting cursor position.
logSleepmessage : string or number or object or any[], type ?: MessageType or "none", ms : numberselfLog message and sleep without adjusting cursor position.
showTabledata : object or object[], collumens ?: string[]selfMoves cursor to current row and runs console.table.
logTabledata : object or object[], collumens ?: string[]selfRuns console.table.
showProgramTitlenoneselfLogs the program defined title at the current row with the given title style.
showSeparatornoneselfLogs the program defined separator with the given info style.
logProgramTitlenoneselfLogs the program defined title with the title style.
logSeparatornoneselfLogs the program defined separator with the given info style.
displayScreen(screen:Screens,args:any)selfLogs the program defined screen at the current
splashScreennoneselfLogs the program defined splashscreen at the current row.
errorScreenmessage : stringselfLogs the program defined error screen at the current row.
crashScreenmessage : stringselfLogs the program defined crash screen at the current row.
promgramInitErrorScreenmessage : stringselfLogs the program defined program init error screen at the current row.

User Input Functions

Functions related to getting the user's input.

dsLog
    .defineValidator(
        "custom",
        async (input: string | string[]) => {
            if (Array.isArray(input)) return false;
            let yes = ["yes", "y"];
            if (yes.indexOf(input) > -1) {
                return true;
            }
            return false;
        },
        "yes"
    )
    .ask("What is your name?", "name", "string")
    .fail(true, "Please re-enter your name.")
    .ask("What is your email?", "name", "email")
    .fail(true, "Please re-enter your email.")
    .ask("Do you agree to the terms?", "terms", "custom", "yes")
    .fail(true, "Are you sure? Please re-enter:", 2, () => {
        dsLog.BR.R.logSleep("Exiting...").exit();
    });
(await dsLog.startPrompt()).BRIGHT.BLUE.logSleep([
    "Your name is:",
    dsLog.getInput("name"),
]);

Question Types

TypeDescription
stringJust chars.
string[]Just an arrary of strings with just chars.
stringallA string of chars and numbers.
stringall[]A string array of chars and numbers.
numberJust numbers.
number[]Just an arrary of numbers.
booleanTrue or false.
boolean[]An array of booleans.
digitJust one digit.
emailAn email.
passwordString of chars and numbers. Output will be hidden.
customAllow for a custom input type. Must define validation later.

Functions

FunctionParamsReturnsDescription
startPromptnonePromise of selfStarts the user input prompt.
restartPromptnoneselfRe-sets the user input prompt.
askquestion : string, varName : string ,varType : QuestionTypes,customName ?: stringselfAdd a question to the prompt. If using a custom question type you must supply the name of the custom type.
failreAsk : boolean, reAskMessage : string,attempts ?: number or "all",onFail ?: Function,arg ?: any = {}selfAnd a fail case to the last asked question. If reAsk is set to false it will run the function supplied and pass it the args supplied.
getInputnonestring or number or undefinedGet input from question
ifInputIssetvarName : string, func : (value:any,args:any)=>{} ,args : anyselfIf a input is set, run a function that will be passed the value and any args you give as the arg object.

User Keyboard Event Functions

User Input Keys

KeyNote
upArrow up.
downArrow down.
leftArrow left.
rightArrow right.
ctrl+aControl + A
ctrl+bControl + B
crtrl+cControl + C
ctrl+dControl + D
ctrl+eControl + E
crtrl+fControl + F
ctrl+gControl + G
ctrl+hControl + H
crtrl+iControl + I
ctrl+jControl + J
ctrl+kControl + K
crtrl+lControl + L
ctrl+mControl + M
ctrl+nControl + N
crtrl+oControl + O
ctrl+pControl + P
ctrl+qControl + Q
crtrl+rControl + R
ctrl+sControl + S
ctrl+tControl + T
crtrl+uControl + U
ctrl+vControl + V
ctrl+wControl + W
crtrl+xControl + X
ctrl+yControl + Y
ctrl+zControl + Z
f1Function 1
f2Function 2
f3Function 3
f4Function 4
f5Function 5
f6Function 6
f7Function 7
f8Function 8
f9Function 9
f10Function 10
f12Function 12
escEscape
endEnd
homeHome
page-upPage Up
page-downPage Down
enterEnter

User Input Watch Object

ParamterType
run(args ?: any)=>{}
argsany

Functions

dsLog
    .startUserInputCaptcher()
    .onUserInputKey("up", {
        run: () => {
            dsLog.INFO.log("up");
        },
    })
    .onUserInputKey("down", {
        run: () => {
            dsLog.INFO.log("down");
        },
    })
    .onUserInputKey("left", {
        run: () => {
            dsLog.INFO.log("left");
        },
    })
    .onUserInputKey("right", {
        run: () => {
            dsLog.INFO.log("right");
        },
    });
FunctionParamsReturnsDescription
startUserInputCaptchernoneselfStart listening to users inputs to run linked functions.
stopUserInputCaptchernoneselfStop listening to users input.
onUserInputCharchar : string,watcher : UserInputWatchObjectselfAdds a function to run when the user enter a specific char.
onUserInputKeykey : UserInputKeys,watcher : UserInputWatchObjectselfAdds a function to run when the user enter a specific key.

Progress Bar

Functions and types related to making a progress bar.

Progress Bar Style

TypeDescription
baseThe base char. Default is "-".
baseStyleA style object for the base char.
loadedA loaded part for the bar. Default is "=".
loadedStyleA style object for the loaded char.
sizeThe size of the progress bar.
intervalThe interval at which the bar fills. Default is 20ms.

Functions

FunctionParamsReturnsDescription
newProgressBarname : string,style ?: ProgressBarStyleselfCreates a new progress bar at the current row with the given name as its id.
incrementProgressBarname: string, amount: numberPromise of selfIncrease the given progress bars progress.

Service Bar

Functions and types related to creating a service bar.

Progres Bar Style

TypeDescription
baseThe base char for the service bar. Default is "X".
baseStyleStyle object for base char.
loadedOneFirst char for load sequence. Default is "0".
loadedOneStyleStyle object for loaded one char.
loadedTwoSecond char for load sequence. Default is "|".
loadedTwoStyleStyle object for loaded two char.
capChar to appear at the end of the service bar.
capStyleStyle for the cap char.
sizeSize of the service bar.
intervalInterval at which the bar loads. Default is 80ms.

Functions

FunctionParamsReturnsDescription
newServiceBarname : string,style ?: ServiceBarStyleselfMakes a continuous loading bar at the given row.
reInitServiceBarname : stringselfResets a service bar.
destroyServiceBarname : stringselfDestroys a service bar.

Stylize Functions

Functions and types related to stylizing text.

Console Colors

Color Name
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White

Style Object

All properties are optional. | Name | Description | | ----------- | ------------------------------------------------------------------------------------ | | fg | Foreground color. Must be a ConsoleColor. | | bg | Background color. Must be a ConsoleColor. | | bright | Makes the colors bright. | | dim | Makes the colors dim. | | underscore| Makes the text underscored. | | blink | Makes the text blink | | reverse | Inverts the foreground and background colors. | | hidden | Makes the text hidden. |

Style Functions

FunctionParamsReturnsDescription
stylizetext : string, styleObj : StyleObjectselfReturns a string stylized with the given format.

Style Short Codes

The functions themselves will just return stylized text made from the chain. If you use the style alias it will set the style for the next set of outputs.

The example below will show a message with a bright red background and white text and then a bright blue background and white text. Notice that the style must be cleared in-between the messages. This is so you can just re-use the same style if you want.

dsLog
    .newScreen()
    .BR.W.RBG.showSleep("Error Message")
    .ERROR.showSleep(["Error Message", "Error Message 1", "Error Message 2"])
    .CLEAR.BR.W.BBG.showSleep("Info Message")
    .INFO.showSleep("Info Message 1")
    .showSleep("This will be the same style")
    .CLEAR.showSleep("This will not be.");

List of All Functions

FunctionDIRECTIVEParamsReturnsDescription
clearCLEAR CLnoneselfReturns a string stylized to be bright.
infoINFOtext : stringstringReturns a string stylized to be the "info" message type.
goodGOODtext : stringstringReturns a string stylized to be the "good" message type.
errorERRORtext : stringstringReturns a string stylized to be the "error" message type
warningWARNINGtext : stringstringReturns a string stylized to be the "warning" message type
titleTITLEtext : stringstringReturns a string stylized to be the "title" message type.
rawRAWtext : stringstringReturns a string stylized to be the "raw" message type.
brightBRIGHT BRtext : stringstringReturns a string stylized to be bright.
dimDIM Dtext : stringstringReturns a string stylized to be dim.
invertINVERT Itext : stringstringReturns a string stylized to invert the background and foreground colors.
underscoreUNDERSCORE UNDERLINE Utext : stringstringReturns a string stylized to be underscored.
hiddenHIDDEN Htext : stringstringReturns a string stylized to be hidden.
blackBLACK BLtext : stringstringReturns a string stylized to be black.
redRED Rtext : stringstringReturns a string stylized to be red.
greenGREEN Gtext : stringstringReturns a string stylized to be green.
yellowYELLOW Ytext : stringstringReturns a string stylized to be yellow.
blueBLUE Btext : stringstringReturns a string stylized to be blue.
magentaMAGENTA Mtext : stringstringReturns a string stylized to be magenta.
cyanCYAN Ctext : stringstringReturns a string stylized to be cyan.
whiteWHITE Wtext : stringstringReturns a string stylized to be white.
blackBGBLACKBG BLBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be black background.
redBGREDBG RBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be red background.
greenBGGREENBG GBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be green background.
yellowBGYELLOWBG YBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be yellow background.
blueBGBLUEBG BBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be blue background.
magentaBGMAGENTABG MBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be magenta background.
cyanBGCYANBG CBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be cyan background.
whiteBGWHITEBG WBGtext : string,fg ?: ConsoleColorstringReturns a string stylized to be white background.

Groups

Directives

NameFunction
GROUPCalls group() and toggles group
GROUPSTART GRSCalls group() and turns sets to true.
GROUPEND GRECalls groupEnd() and turns sets to false.
GROUPENDALL GREA COLLAPSEALLGROUPS CAGCalls endAllGroups() and sets group to false.

Functions

FunctionParamsReturnsDescription
grouplabel ?: string, styleObj ?: StyleObjectselfCalls console.group. If the the label or the styleObject is set it will use that to for a heading.
endGroupselfCalls console.endGroup once.
endAllGroups or collapseAllGroupsselfCalls console.endGroup to collapse all groups.

Debug

NameFunction
DEBUGToggles debug and will only show the following message if debug mode is enabled. Chain again to disable.
DEBUGSTARTTurns debug to true and will only show the following message if debug mode is enabled.
DEBUGENDTurns debug to false.
TRACEToggles trace. Run again to disable. Will show all message using console.trace.
TRACESTART TSStart using console.trace.
TRACEEND OR TEStop using console.trace.
TIMERuns time()
TIME ENDRuns timeEnd()

Functions

    dsLog
        .debug()
        .DEBUG.logSleep(["This messages will log", "when debug is true"])
        .DEBUG.TRACE.log(["This message will be logged with console.trace."])
        .TRACE.TIME.sleep(2000).TIMEEND.DIE;
FunctionParamsReturnsDescription
debugdebug ?: boolean = trueselfStarts debug mode or disables it.
tracedebug ?: boolean = trueselfselfStarts trace mode or disables it.
timelabel ?: string = "default"selfCalls console.time with the given label.
timeEndlabel ?: string = "default"selfCalls console.timeEnd with the given label.

Directives

Directives are all cap vars in the class that will do things if you get them. In the style section each color and output style has it's own directive which can be called to stylize the next output. Every directive will just return DSLogger so you can chain them together.

Below are other directives and their uses.

dsLog.NS.BR.W.logSleep([
    "This will clear the screen",
    "log bright white text ",
    "and then stop",
]).NL.EXIT;
NameDescription
NS NEWSCREENRuns clearScreen.
NL NEWLINE RETURNPrints a new line to the console.
EXIT DIE ENDRuns exit.

Define and Get Functions

Functions related to setting default strings, screens, and validation. This is for full customization of the program.

Strings

Built in strings. | Name | Description | | ----------- | ------------------------------------------------------------------------------------ | | title | Title of the program. | | helpText | Text used for the help screen. | | star | Star art. | | seperator| The seperator displayed when using logSeperator() | | questionStart | The string that appears at the start of a question. | | questionDelimiter | The string that appears at the end of a question. | | reAskStart | The string that appears at the start of a re-ask. | | reAskText | The string that appears as the default for a re-ask. | | reAskDelimiter | The string that appears at the end of a re-ask. |

QuestionDisplayTypes

Defined styles for the question outputs. | Name | Description | | ----------- | ------------------------------------------------------------------------------------ | | question-star | Style for question start string. | | question | Style for questions. | | delimiter | Style for question delimiter. | | re-ask-start| Style for re-ask start | | re-ask | Style for re-ask. | | re-ask-delimiter | Style for re-ask delimiter |

Screens

Built in screens. | Name | Description | | ----------- | ------------------------------------------------------------------------------------ | | splash | The program splash screen. | | programInitError | Program init error screen. | | helpScreen | A userful help screen generated from the program params. | | crash | A crash screen. | | done | A screen to show when the program is done. | | noInput | a screen to show when the program runs with no input. |

Functions

FunctionParamsReturnsDescription
defineValidatortype : QuestionTypes, func : (input:string)=Promise\<boolean>, customName : stringselfDefine the function to be called to validate input.
defineSleepTimesleep : number,selfDefine the default sleep time in ms.
defineScreenscreen : Screens, func : FunctionselfDefine the function to be called for a screen.
defineSplashScreenfunc : FunctionselfDefine the function to be called for the splash screen. This function is just to make it easy cause it is the most common screen to adjust.
defineProgramTitletitle : string, styleObj: StyleObjectselfDefines the programs title and optionally the style
defineHelpTexttext : stringselfDefines the programs help text.
defineQuestionStyletype: QuestionDisplayTypes, styleObj: StyleObjectselfUse a style object to define a questions style.
defineMessageStyletype: MessageTypes, styleObj: StyleObjectselfSet a style object to define a message style.
defineProgressBarStylestyle: ProgressBarStyleselfDefine the default progress bar style.
defineServiceBarStylestyle: ServiceBarStyleselfDefine the default service bar style.
getStringname : StringselfGet a built in string.
setStringname : String, string : stringselfSet a built in string.

Row and Collumn Functions

Functions related to the output row.

FunctionParamsReturnsDescription
getRownonenumberGets the current output row.
setRowrow : numberselfSets the output row.
addRownoneselfAdds one to the current output row.
minusRownoneselfMinus one to the current output row.
getColnonenumberGets the current output collumn.
setColrow : numberselfSets the output collumn.
addColnoneselfAdds one to the current output collumn.
minusColnoneselfMinus one to the current output collumn.
clearRowsstart : number, end : numberselfClears given row range.

Sleep Functions

Functions used to make the program sleep.

FunctionParamsReturnsDescription
sleepms : numberselfMake the progarm sleep via a sync method.
asyncSleepms : numberPromise of selfMake the program sleep via an async method.

Do and Service Functions

Used for running a function in the command chain or starting a service. A service is just some code that runs on an interval.

dsLog
    .defineSleepTime(200)
    .do(() => {
        dsLog.BRIGHT.GREEN.logSleep(["do", "some", "stuff"]).CLEAR;
    })
    .newService("service-1", {
        interval: 2000,
        run: (args: any) => {
            args.count++;
            dsLog.NEWSCREEN.DIM.MAGENTA.UNDERLINE.logSleep(
                `RAN : ${args.count} TIMES`
            ).CLEAR.DIM.CYAN.logSleep(["running", "the", "service"]);
        },
        args: { count: 0 },
    });
FunctionParamsReturnsDescription
dofunc : (arg:any)=>any,arg ?: anyselfRun a function in the chain.
newServicename : string , params : {interval : number,run : func : (arg:any)=>any,arg : any }selfRun a function in the chain on an interval.
clearServicename : stringselfStops a service from running.

Other Functions

Other usefull functions.

FunctionParamsReturnsDescription
exitnonenoneRuns process.exit(0).
donenonenoneShows the done screen and then exits.
countLinestext : stringnumberCount the numbers of lines in a string.
1.1.6

3 years ago

1.1.5

3 years ago

1.1.52

3 years ago

1.1.51

3 years ago

1.1.54

3 years ago

1.1.53

3 years ago

1.1.541

3 years ago

1.1.41

3 years ago

1.1.42

3 years ago

1.1.4

3 years ago

1.1.36

3 years ago

1.1.35

3 years ago

1.1.34

3 years ago

1.1.33

3 years ago

1.1.32

3 years ago

1.1.31

3 years ago

1.1.3

3 years ago

1.1.21

3 years ago

1.1.2

3 years ago

1.1.11

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.9

3 years ago

1.0.81

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.604

3 years ago

1.0.603

3 years ago

1.0.602

3 years ago

1.0.601

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.0

3 years ago