Installation
npm i kaven-utils --save
Usage
import * as kavenUtils from "kaven-utils";
kavenUtils.OverrideConsole();
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();
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));
}
}
}
if (false) {
KavenUtility.RunTest(() => {
console.log(KavenUtility.GenerateRandomString(10));
}, 2);
}
if (false) {
const total = 10000;
let count = total;
const ids1: string[] = [];
const t0 = performance.now();
while (count-- > 0) {
const id = KavenUtility.GenerateYearMonthId(4, id => {
if (ids1.includes(id)) {
return false;
}
return true;
});
ids1.push(id);
}
const t1 = performance.now();
count = total;
const ids2: string[] = [];
const t2 = performance.now();
const guid = KavenUtility.GenerateGuid();
while (count-- > 0) {
const id = KavenUtility.GenerateYearMonthId(4, undefined, ids2, guid);
ids2.push(id);
}
KavenUtility.RemoveCache(guid);
const t3 = performance.now();
console.log(`${t1 - t0}ms, ${t3 - t2}ms`);
}
if (false) {
(async function () {
const total = 100;
let count = total;
const ids1: string[] = [];
const t0 = performance.now();
while (count-- > 0) {
const id = await KavenUtility.GenerateYearMonthIdAsync(4, id => {
if (ids1.includes(id)) {
console.warn(`ID already exist: ${id}`);
return Promise.resolve(false);
}
return Promise.resolve(true);
});
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 id = await KavenUtility.GenerateYearMonthId(4, undefined, ids2, guid);
ids2.push(id);
console.log(`${total - count}: ${id}`);
}
KavenUtility.RemoveCache(guid);
const t3 = performance.now();
console.log(`${t1 - t0}ms, ${t3 - t2}ms`);
})();
}
if (false) {
let backupDir;
KavenUtility.BackupMongoDB("Z:\\123\\Backup\\222", "DB")
.then<string>(success => {
console.log(`MongoDB dump: ${success}`);
backupDir = success;
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]}`);
const pwd = "password for temp@wuwenkai.com";
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>";
KavenUtility.SendEmail(mailConfig, mailOption);
}).catch(err => {
console.error(err);
});
}
if (false) {
KavenUtility.SevenZipFolder("Z:\\123",
`Z:\\temp\\${KavenUtility.GetFileNameByDateTime()}.7z`,
"12345"
)
.then(success => {
console.log(success);
}).catch(err => {
console.error(err);
});
}
if (false) {
KavenUtility.RunTest(() => {
console.log(KavenUtility.GeneratePassword(10, true, true, true, false));
}, 100);
}
if (false) {
const link = "http://kavenblog.com";
KavenUtility.GenerateQRCode(link).then(code => {
console.log(code);
}).catch(err => {
console.error(err);
});
}
if (false) {
KavenUtility.StartSchedule(() => {
console.log("exec");
}, undefined, undefined, undefined, undefined, undefined, undefined, KavenUtility.CreateArray(10, 0, 2));
}
if (false) {
const temp = KavenUtility.Base64Encode("some test data");
console.log(KavenUtility.Base64Decode(temp));
console.log(KavenUtility.Base64Decode("Ny4xLjguMTE=", "ascii"));
}
if (false) {
(async function () {
const key = await KavenUtility.CreateCertificate({ days: 365 * 10, selfSigned: true });
await KavenUtility.SaveStringToFile(key.serviceKey, "Z:/temp/gogs.pem");
await KavenUtility.SaveStringToFile(key.certificate, "Z:/temp/gogs.cert");
}());
}
if (false) {
const str = "Unknown word: \"check\"";
console.log(KavenUtility.GetStringBetween(str, "\"", "\""));
}
if (false) {
KavenUtility.WriteStringToClipboard(KavenUtility.GetFileNameByDateTime());
console.log(KavenUtility.ReadStringFromClipboard());
KavenUtility.WriteStringToClipboardAsync(KavenUtility.GetFileNameByDateTime()).then(() => {
KavenUtility.ReadStringFromClipboardAsync().then(text => {
console.log(text);
});
});
}
if (false) {
console.log("_" + " asd".GetIndent() + "_");
}
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);
});
}