Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

kaven-utils

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kaven-utils

Utils for Node.js.

  • 1.1.0
  • npm
  • Socket score

Version published
Weekly downloads
7
decreased by-12.5%
Maintainers
1
Weekly downloads
 
Created
Source

Installation

npm i kaven-utils --save

Usage

import * as kavenUtils from "kaven-utils";
kavenUtils.OverrideConsole();

// Create Express server
const app = express();
app.use(kavenUtils.Logger);

Release Notes

1.0.8

Add clipboard support base on clipboardy

Add following functions:

export declare function WriteStringToClipboard(text: string): void;
export declare function WriteStringToClipboardAsync(text: string): Promise<void>;
export declare function ReadStringFromClipboard(): string;
export declare function ReadStringFromClipboardAsync(): Promise<string>;
export declare function SplitStringByNewline(str: string): string[];

1.0.9

Add following functions:

export declare function RemoveInvalidCharactersForPath(path: string): string;
export declare function DownloadFile(url: string, path: string): Promise<string>;
export declare function GetFileSizeInBytes(path: string): Promise<number>;
export declare function ResetLogFileIf(overBytes?: number): Promise<boolean>;
export declare function MakeDirectory(dir: string): Promise<string>;
export declare function MakeDirectorySync(dir: string): string;

1.0.10

Add following functions:

interface String {
    GetIndent(): string;
}

1.0.11

Add:

export declare let IsDebugMode: boolean;

Improve:

export declare function CopyFileSync(dest: string, src: string): any;

1.0.12

1.0.13

1.0.14 (republish)

Add:

interface String {
    OnlyContains(...characters: string[]): boolean;
    ToArray(): string[];
    Distinct(): string;
}

interface Array < T > {
    Distinct(): Array < T > ;
    First(): T;
    Last(): T;
}

export declare let IsDebugMode: boolean;
export declare function LoadJsonFile(path: string): Promise<{[index: string]: any;}>;
export declare function GetNextVersion(version: string): string | number;

1.1.0

Add:

export declare namespace KavenCommon
export declare namespace KavenUtility
export default KavenUtility;

Dependencies

Example

import KavenUtility, { BitString, MailConfig, MailOption } from "kaven-utils";
import { performance } from "perf_hooks";

KavenUtility.OverrideConsole();

// console.log(Number.MAX_VALUE);
// console.log(utils.HttpStatusCode.InternalServerError);
// console.log(utils.Strings.HTML_BR);

//#region BitString Test

if (false) {
    const bitStr = new BitString();

    let count = 5;
    while (count-- > 0) {
        for (let i = 1; i < 100; i++) {
            console.log(bitStr.SetBit(i, KavenUtility.RandomBoolean()).toString());
        }

        for (let i = 1; i < 100; i++) {
            console.log(bitStr.GetBit(i));
        }
    }
}

//#endregion

//#region GenerateRandomString Test

if (false) {
    KavenUtility.RunTest(() => {
        console.log(KavenUtility.GenerateRandomString(10));
    }, 2);
}

//#endregion

//#region GenerateYearMonthId Test

if (false) {
    const total = 10000;
    let count = total;
    const ids1: string[] = [];

    const t0 = performance.now();
    while (count-- > 0) {

        // const start = performance.now();
        const id = KavenUtility.GenerateYearMonthId(4, id => {
            // return !ids.includes(id);
            if (ids1.includes(id)) {
                // console.warn(`ID already exist: ${id}`);
                return false;
            }

            return true;
        });
        // console.log(`====== 1: ${performance.now() - start}`);

        ids1.push(id);
        // console.log(`${total - count}: ${id}`);
    }
    const t1 = performance.now();

    count = total;
    const ids2: string[] = [];

    const t2 = performance.now();
    const guid = KavenUtility.GenerateGuid();
    while (count-- > 0) {
        // const start = performance.now();
        const id = KavenUtility.GenerateYearMonthId(4, undefined, ids2, guid);
        // console.log(`====== 2: ${performance.now() - start}`);

        ids2.push(id);
        // console.log(`${total - count}: ${id}`);
    }
    KavenUtility.RemoveCache(guid);
    const t3 = performance.now();

    console.log(`${t1 - t0}ms, ${t3 - t2}ms`);
}
//#endregion

//#region GenerateYearMonthIdAsync Test

if (false) {
    // https://github.com/tc39/ecmascript-asyncawait/issues/9
    (async function () {
        const total = 100;
        let count = total;
        const ids1: string[] = [];

        const t0 = performance.now();
        while (count-- > 0) {

            // const start = performance.now();
            const id = await KavenUtility.GenerateYearMonthIdAsync(4, id => {
                // return !ids.includes(id);
                if (ids1.includes(id)) {
                    console.warn(`ID already exist: ${id}`);
                    return Promise.resolve(false);
                }

                return Promise.resolve(true);
            });
            // console.log(`====== 1: ${performance.now() - start}`);

            ids1.push(id);
            console.log(`${total - count}: ${id}`);
        }
        const t1 = performance.now();

        count = total;
        const ids2: string[] = [];

        const t2 = performance.now();
        const guid = KavenUtility.GenerateGuid();
        while (count-- > 0) {
            // const start = performance.now();
            const id = await KavenUtility.GenerateYearMonthId(4, undefined, ids2, guid);
            // console.log(`====== 2: ${performance.now() - start}`);

            ids2.push(id);
            console.log(`${total - count}: ${id}`);
        }
        KavenUtility.RemoveCache(guid);
        const t3 = performance.now();

        console.log(`${t1 - t0}ms, ${t3 - t2}ms`);
    })();
}
//#endregion

//#region DB backup

if (false) {

    let backupDir;
    KavenUtility.BackupMongoDB("Z:\\123\\Backup\\222", "DB")
        .then<string>(success => {
            console.log(`MongoDB dump: ${success}`);
            backupDir = success;
            // return utils.ZipFolder(success, utils.ChangeFileExtension(success, "zip"));
            return KavenUtility.SevenZipFolder(success, KavenUtility.ChangeFileExtension(success, "7z"), "123456");
        })
        .then(success => {
            console.log(`Create ZIP file: ${success}`);
            return Promise.all([KavenUtility.DeleteFolder(backupDir), KavenUtility.UploadFileToFTPServer(success, "127.0.0.1", 21, "test", "123456")]);
        }).then(values => {
            console.log(`Delete ${values[0].length} files.`);
            console.log(`Upload to FTP: ${values[1]}`);

            /* cSpell:disable */
            const pwd = "password for temp@wuwenkai.com";
            /* cSpell:enable */

            const mailConfig = new MailConfig("smtp.mxhichina.com", 25, false, "temp@wuwenkai.com", pwd);
            const mailOption = new MailOption("temp@wuwenkai.com", "kavenwork@gmail.com", "Test", "Test Email", "");

            mailOption.HTML = "<b>DB backup success.</b>";

            // mailConfig.Verify();
            KavenUtility.SendEmail(mailConfig, mailOption);

        }).catch(err => {
            console.error(err);
        });


    // utils.ZipFolder("Z:\\123", "Z:\\666.zip").then(success => {
    //     console.log(success);
    // }, err => {
    //     console.error(err);
    // });
}

//#endregion

//#region 7z

if (false) {
    // utils.SevenZipFiles(["Z:\\123\\HID.exe", "Z:\\123\\media\\0ecad205df88143d691b4851fcbbb52f.png"],
    //     `Z:\\temp\\${utils.GetFileNameByDateTime()}.7z`).then(success => {
    //         console.log(success);
    //     }).catch(err => {
    //         console.error(err);
    //     });

    KavenUtility.SevenZipFolder("Z:\\123",
        `Z:\\temp\\${KavenUtility.GetFileNameByDateTime()}.7z`,
        "12345"
    )
        .then(success => {
            console.log(success);
        }).catch(err => {
            console.error(err);
        });
}

//#endregion

//#region GeneratePassword Test

if (false) {
    KavenUtility.RunTest(() => {
        console.log(KavenUtility.GeneratePassword(10, true, true, true, false));
    }, 100);
}

//#endregion

//#region QR Code

if (false) {
    const link = "http://kavenblog.com";
    KavenUtility.GenerateQRCode(link).then(code => {
        console.log(code);
    }).catch(err => {
        console.error(err);
    });
}

//#endregion

//#region Schedule

if (false) {
    KavenUtility.StartSchedule(() => {
        console.log("exec");
    }, undefined, undefined, undefined, undefined, undefined, undefined, KavenUtility.CreateArray(10, 0, 2));
}

//#endregion

//#region base64

if (false) {
    const temp = KavenUtility.Base64Encode("some test data");
    console.log(KavenUtility.Base64Decode(temp));

    /* cSpell:disable */
    console.log(KavenUtility.Base64Decode("Ny4xLjguMTE=", "ascii"));
    /* cSpell:enable */
}

//#endregion

//#region CreateCertificate

if (false) {
    (async function () {
        const key = await KavenUtility.CreateCertificate({ days: 365 * 10, selfSigned: true });
        // console.log(key);

        await KavenUtility.SaveStringToFile(key.serviceKey, "Z:/temp/gogs.pem");
        await KavenUtility.SaveStringToFile(key.certificate, "Z:/temp/gogs.cert");
    }());
}

//#endregion

//#region GetStringBetween

if (false) {
    const str = "Unknown word: \"check\"";
    console.log(KavenUtility.GetStringBetween(str, "\"", "\""));
}

//#endregion

//#region Clipboard

if (false) {
    KavenUtility.WriteStringToClipboard(KavenUtility.GetFileNameByDateTime());
    console.log(KavenUtility.ReadStringFromClipboard());

    KavenUtility.WriteStringToClipboardAsync(KavenUtility.GetFileNameByDateTime()).then(() => {
        KavenUtility.ReadStringFromClipboardAsync().then(text => {
            console.log(text);
        });
    });
}


//#endregion

//#region GetIndent
if (false) {
    console.log("_" + "     asd".GetIndent() + "_");
}
//#endregion

if (true) {
    KavenUtility.LoadJsonFile("./package.json").then(data => {
        const version = data["version"];
        console.log(version);
        console.log(KavenUtility.GetNextVersion(version))
    }).catch (ex => {
        console.error(ex);
    });
}


Keywords

FAQs

Package last updated on 09 Aug 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc