@agds/node-utils
TypeScript icon, indicating that this package has built-in type declarations

1.0.18 • Public • Published

logo

@agds/node-utils

版本 :1.0.18

agds系统内部node工具函数库

快速开始

安装

npm i @agds/node-utils

引入

const utils = require('@agds/node-utils');
const { ConvName, FastPath, FastFs, Notice, PresetUtils, GitUtils, NpmUtils, CmdUtils } = utils;

导出

module.exports = { ConvName, FastPath, FastFs, Notice, PresetUtils, GitUtils };

代码演示

const { expect, test, describe } = require('@jest/globals');
const { ConvName, FastFs, FastPath, Notice, PresetUtils, CmdUtils, GitUtils, NpmUtils } = require('@agds/node-utils');
const path = require('path');
const fs = require('fs-extra');
describe('ConvName', () => {
    test('ConvName.initName', () => {
        const convName = ConvName.initName('ConvName-test');
        expect(convName).toMatchObject({
            lineName: 'conv-name-test',
            humpName: 'ConvNameTest',
            lowerHumpName: 'convNameTest',
        });
    });
    test('class ConvName', () => {
        const convName = new ConvName('ConvName-test');
        expect(convName).toMatchObject({
            lineName: 'conv-name-test',
            humpName: 'ConvNameTest',
            lowerHumpName: 'convNameTest',
        });
    });
    test('ConvName.toLine', () => {
        const name = ConvName.toLine('ConvName-test');
        expect(name).toBe('conv-name-test');
    });
    test('ConvName.toLowerHump', () => {
        const name = ConvName.toLowerHump('ConvName-test');
        expect(name).toBe('convNameTest');
    });
    test('ConvName.toUpperHump', () => {
        const name = ConvName.toUpperHump('ConvName-test');
        expect(name).toBe('ConvNameTest');
    });
});

const testText = 'Test';
describe('FastFs', () => {
    test('FastFs.writeFile', async () => {
        const pathName = path.join(__dirname, '.temp/FastFs.writeFile.test');
        await FastFs.writeFile(pathName, testText);
        expect(fs.readFileSync(pathName, { encoding: 'utf-8' })).toBe(testText);
    });
    test('FastFs.writeFileSync', () => {
        const pathName = path.join(__dirname, '.temp/FastFs.writeFileSync.test');
        FastFs.writeFileSync(pathName, testText);
        expect(fs.readFileSync(pathName, { encoding: 'utf-8' })).toBe(testText);
    });
    const statPathName = path.join(__dirname, '../__mock__/index.js');
    const statFalsePathName = path.join(__dirname, '../__mock__/index.jst');

    test('FastFs.getPathStat', async () => {
        const res = await FastFs.getPathStat(statPathName);
        expect(res).toBe(true);
    });
    test('FastFs.getPathStat false', async () => {
        const res = await FastFs.getPathStat(statFalsePathName);
        expect(res).toBe(false);
    });
    test('FastFs.getPathStatSync', () => {
        const res = FastFs.getPathStatSync(statPathName);
        expect(res).toBe(true);
    });
    test('FastFs.getPathStatSync false', () => {
        const res = FastFs.getPathStatSync(statFalsePathName);
        expect(res).toBe(false);
    });
    const obj = {
        a: 'a',
        b: 1,
    };
    test('FastFs.writeJsonFormat&FastFs.readJson', async () => {
        const pathName = path.join(__dirname, '.temp/FastFs.writeJsonFormat.json');
        await FastFs.writeJsonFormat(pathName, obj);
        expect(await FastFs.readJson(pathName)).toMatchObject(obj);
    });
    test('FastFs.writeJsonFormatSync&FastFs.readJsonSync', () => {
        const pathName = path.join(__dirname, '.temp/FastFs.writeJsonFormatSync.json');
        FastFs.writeJsonFormatSync(pathName, obj);
        expect(FastFs.readJsonSync(pathName)).toMatchObject(obj);
    });
    const json = require('../__mock__/json.json');
    const jsonPathName = path.join(__dirname, '../__mock__/json.json');
    test('FastFs.readJson', async () => {
        const res = await FastFs.readJson(jsonPathName);
        expect(res).toMatchObject(json);
    });
    test('FastFs.readJsonSync', () => {
        const res = FastFs.readJsonSync(jsonPathName);
        expect(res).toMatchObject(json);
    });
    test('FastFs parseJson error', () => {
        const jsonPathName = path.join(__dirname, '../__mock__/index.js');
        try {
            FastFs.readJsonSync(jsonPathName);
        } catch (error) {
            expect(error.message).toMatch(jsonPathName);
        }
    });
    test('FastFs.sortDependencies', () => {
        FastFs.sortDependencies(path.join(__dirname, '../__mock__/test-package.json'));
        expect(true).toBe(true);
    });
});

describe('FastPath', () => {
    test('FastPath.getCwdPath', () => {
        const res = FastPath.getCwdPath('package.json');
        expect(typeof res === 'string').toBe(true);
    });
    test('FastPath.getHomePath', () => {
        const res = FastPath.getHomePath('cache');
        expect(typeof res === 'string').toBe(true);
    });
    test('FastPath.getagdsHomePath', () => {
        const res = FastPath.getAgdsHomePath('cache');
        expect(typeof res === 'string').toBe(true);
    });
    test('FastPath.convPath', () => {
        const res = FastPath.convPath(__dirname, 'cache');
        expect(typeof res === 'string').toBe(true);
    });
    test('FastPath.convPath root', () => {
        const res = FastPath.convPath(__dirname, '/cache');
        expect(typeof res === 'string').toBe(true);
    });
});
describe('Notice', () => {
    const onConsoleOut = (logMethod, cb, out) => new Promise(resolve => {
        const log = console[logMethod];
        console[logMethod] = function () {
            // log.apply(console, arguments);
            cb.apply(null, arguments);
            resolve();
            console[logMethod] = log;
        };
        out();
    });
    test('Notice.success', () => {
        return onConsoleOut('log', (res) => {
            expect(JSON.stringify(res)).toBe('"\\u001b[42m\\u001b[30m SUCCESS \\u001b[39m\\u001b[49m\\u001b[32m 成功信息\\u001b[39m"');
        }, () => Notice.success('成功信息'));
    });
    test('Notice.error', () => {
        return onConsoleOut('error', (res) => {
            expect(JSON.stringify(res)).toBe('"\\u001b[41m ERROR \\u001b[49m\\u001b[31m 错误信息\\u001b[39m"');
        }, () => Notice.error('错误信息'));
    });
    test('Notice.warn', () => {
        return onConsoleOut('warn', (res) => {
            expect(JSON.stringify(res)).toBe('"\\u001b[43m\\u001b[30m WARN \\u001b[39m\\u001b[49m\\u001b[33m 警告信息\\u001b[39m"');
        }, () => Notice.warn('警告信息'));
    });
    test('Notice.info', () => {
        return onConsoleOut('info', (res) => {
            expect(JSON.stringify(res)).toBe('"\\u001b[44m\\u001b[30m INFO \\u001b[39m\\u001b[49m\\u001b[36m 普通信息\\u001b[39m"');
        }, () => Notice.info('普通信息'));
    });
    test('Notice.getStr', () => {
        const res = Notice.getStr('info', '普通信息颜色文字');
        expect(JSON.stringify(res)).toBe('"\\u001b[36m普通信息颜色文字\\u001b[39m"');
    });
    test('Notice.getBoldStr', () => {
        const res = Notice.getBoldStr('blue', '普通信息颜色文字');
        expect(JSON.stringify(res)).toBe('"\\u001b[1m\\u001b[34m普通信息颜色文字\\u001b[39m\\u001b[22m"');
    });
});

describe('PresetUtils', () => {
    const config = {
        presets: [{
            e: 'e',
            b: ['b'],
            c: 'c',
        }],
        a: 'a',
        c: 'd',
        b: [
            'a',
            'c',
        ],
        modify: (_config) => {
            delete _config.c;
        },
    };
    test('PresetUtils.getDeepPreset', async () => {
        const res = await PresetUtils.getDeepPreset(config);
        expect(res).toMatchObject([
            { e: 'e', b: ['b'], c: 'c' },
            { presets: [{ e: 'e', b: ['b'], c: 'c' }], a: 'a', c: 'd', b: ['a', 'c'] },
        ]);
    });
    test('PresetUtils.getDeepPresetMerge', async () => {
        const res = await PresetUtils.getDeepPresetMerge(config);
        expect(res).toMatchObject({ a: 'a', b: ['b', 'a', 'c'], c: 'd', e: 'e' });
    });
    test('PresetUtils.getDeepPresetMergeAndModify', async () => {
        const res = await PresetUtils.getDeepPresetMergeAndModify(config);
        expect(res).toMatchObject({ a: 'a', b: ['b', 'a', 'c'], e: 'e' });
    });
});

describe('CmdUtils', () => {

    test('CmdUtils.runCommand', () => {
        return CmdUtils.runCommand('cat', [path.join(__dirname, '../__mock__/test-package.json')]).then(() => {
            expect(true).toBe(true);
        });
    });
    test('CmdUtils.runCommand error', () => {
        return CmdUtils.runCommand('aaa').catch((e) => {
            expect(e.message).toMatch('aaa' + '执行失败');
        });
    });
});

describe('GitUtils', () => {
    test('GitUtils.getUser', () => {
        const user = GitUtils.getUser();
        expect(Object.values(user).map(v => typeof v).join(' ')).toBe(new Array(3).fill('string').join(' '));
    });
});

describe('NpmUtils', () => {
    const packageName = '@agds/node-utils';
    const version = '1.0.14';
    test('NpmUtils.getRegistry', () => {
        const res = NpmUtils.getRegistry();
        expect(typeof res).toBe('string');
    });
});

API文档

nodeUtils

nodeUtils.CmdParser

基于commander.js封装的命令行解析工具库

性质: nodeUtils的静态class

CmdParser.optionParseByConfig(program, config)

基于config配置Command实例

性质: CmdParser的静态方法

参数 类型 描述
program Command command实例
config CmdConfig 命令行解析配置

CmdConfig : object

命令行解析配置

性质: optionParseByConfig的类型声明

属性

属性 类型 描述
cmd string 作为插件时为子命令名称,单独使用时agds-<cmd>为命令行程序名称
desc string 描述
alias string 此命令的别名,只在插件调用时有效
opts Array.<OptConfig> option配置项描述
args Array.<ArgConfig> option配置项描述

OptConfig : object

命令行option解析配置

性质: optionParseByConfig的类型声明

属性

属性 类型 描述
opt string option字段配置
desc string 描述
default string | boolean 默认值
required boolean 是否是必填参数

ArgConfig : object

命令行option解析配置

性质: optionParseByConfig的类型声明

属性

属性 类型 描述
arg string option字段配置
desc string 描述
default string | boolean 默认值

CmdParser.cmdParser(options) ⇒ Command

基于配置文件的命令行解析器

性质: CmdParser的静态方法

参数 类型 描述
options object 函数参数
options.root string 当前命令行npm包根目录
[options.isCore] boolean 是否是@agds/cli调用
[options.cmd] string 命令名称,命令调用必填

nodeUtils.CmdUtils

运行命令行的工具集

性质: nodeUtils的静态class

CmdUtils.installDependencies(options, prod, [executable]) ⇒ Promise.<void>

在项目中执行 npm install

性质: CmdUtils的静态方法

参数 类型 默认值 描述
options module:child_process~SpawnOptions spawn函数的选项参数
prod boolean 是否只下载生产依赖
[executable] 'npm' | 'yarn' | string npm 依赖下载工具,可选值:'npm','yarn'或其他node包管理命令

CmdUtils.runCommand(cmd, args, options) ⇒ Promise.<void>

生成一个子进程并运行指定的命令 默认情况下,运行在CWD和'inherit'的stdio 选项与node的child_process.spawn相同

性质: CmdUtils的静态方法

参数 类型 描述
cmd string 命令
args Array.<string> 参数数组
options module:child_process~SpawnOptions spawn函数的选项参数

nodeUtils.ConvName

名称处理工具类,命名格式转换

性质: nodeUtils的静态class

new ConvName(name)

获取三种名称转换结果的集合

参数 类型 描述
name stirng 名称文本

convName.lineName : string

横杠名称

性质: ConvName的instance属性

convName.humpName : string

大驼峰名称

性质: ConvName的instance属性

convName.lowerHumpName : string

小驼峰名称

性质: ConvName的instance属性

ConvName.toUpperHump(name) ⇒ string

横杠转大驼峰

性质: ConvName的静态方法

参数 类型 描述
name string 名称文本

ConvName.toLowerHump(name) ⇒ string

横杠转小驼峰

性质: ConvName的静态方法

参数 类型 描述
name string 名称文本

ConvName.toLine(name) ⇒ string

驼峰转换横杠

性质: ConvName的静态方法

参数 类型 描述
name string 名称文本

ConvName.initName(name) ⇒ ConvName

获取驼峰和横杠名称

性质: ConvName的静态方法

参数 类型 描述
name string 名称文本

nodeUtils.FastFs

文件系统操作类,集合了几个使用频率较高的文件操作函数

性质: nodeUtils的静态class

FastFs.writeFile(filename, data) ⇒ Promise.<void>

异步写入数据,不存在的路径自动创建

性质: FastFs的静态方法

参数 类型 描述
filename fs.PathLike 文件名
data object 写入的数据(对象)

FastFs.writeFileSync(filename, data) ⇒ void

同步写入数据,不存在的路径自动创建

性质: FastFs的静态方法

参数 类型 描述
filename fs.PathLike 文件名
data object 写入的数据(对象)

FastFs.getPathStat(path) ⇒ Promise.<boolean>

异步获取路径是否存在

性质: FastFs的静态方法

参数 类型 描述
path fs.PathLike 路径

FastFs.getPathStatSync(path) ⇒ boolean

同步获取路径是否存在

性质: FastFs的静态方法

参数 类型 描述
path fs.PathLike 路径

FastFs.writeJsonFormat(filename, data, [space]) ⇒ Promise

异步写入符合.json格式的json文件

性质: FastFs的静态方法

参数 类型 默认值 描述
filename fs.PathLike 文件路径
data any 需要写入的数据
[space] string | number 2 指定缩进用的空白字符串

FastFs.writeJsonFormatSync(filename, data, [space]) ⇒ void

同步写入符合.json格式的json文件

性质: FastFs的静态方法

参数 类型 默认值 描述
filename fs.PathLike 文件路径
data any 需要写入的数据
[space] string | number 2 指定缩进用的空白字符串

FastFs.readJson(filename) ⇒ Promise.<object>

异步读取json文件

性质: FastFs的静态方法

参数 类型 描述
filename fs.PathLike json文件路径

FastFs.readJsonSync(filename) ⇒ object

同步读取json文件

性质: FastFs的静态方法

参数 类型 描述
filename fs.PathLike json文件路径

FastFs.sortDependencies(packageJsonFile)

对packageJson的依赖对象进行key的排序

性质: FastFs的静态方法

参数 类型 描述
packageJsonFile string packageJson文件绝对路径

nodeUtils.FastPath

路径工具类,快速获取各类node常用路径,每个方法要求路径都不是绝对路径 如果是绝对路径,就按照绝对路径拼接

性质: nodeUtils的静态class

FastPath.getCwdPath(...paths) ⇒ string

获取运行目录加路径的绝对路径

性质: FastPath的静态方法

参数 类型 描述
...paths string 路径

FastPath.getHomePath(...paths) ⇒ string

获取用户目录加路径的绝对路径

性质: FastPath的静态方法

参数 类型 描述
...paths string 路径

FastPath.getAgdsHomePath(...paths) ⇒ string

获取用户目录加路径的绝对路径

性质: FastPath的静态方法

参数 类型 描述
...paths string 路径

FastPath.convPath(basePath, paths) ⇒ string

基于基础路径拼接追加路径,如果追加路径数组第一个路径是绝对路径,忽略基础路径直接拼接返回
是其他函数的依赖函数

性质: FastPath的静态方法

参数 类型 描述
basePath string 基础路径
paths Array.<string> 追加路径数组

nodeUtils.GitUtils

Git工具集合

性质: nodeUtils的静态class

GitUtils.gcHasMsg() ⇒ boolean

判断git commit是否传入-m参数 配合yorkie使用,不支持识别husky

性质: GitUtils的静态方法

GitUtils.getUser() ⇒ UserObj

获取当前git用户名称

性质: GitUtils的静态方法 返回值: UserObj - git用户名对象

UserObj : object

git用户名对象

性质: getUser的类型声明

属性

属性 类型 描述
name string 名字
email string 电子邮箱
all string {name}<{email}>

nodeUtils.Notice

基于chalk封装的控制台输出静态函数类

性质: nodeUtils的静态class

ChalkType : 'success' | 'error' | 'warn' | 'info' | string

chalk类型以及别名

性质: Notice的类型声明

Notice.success(msg) ⇒ void

控制台输出成功信息

性质: Notice的静态方法

参数 类型 描述
msg string 成功信息

Notice.error(msg) ⇒ void

控制台输出错误信息

性质: Notice的静态方法

参数 类型 描述
msg string 错误信息文本

Notice.warn(msg) ⇒ void

控制台输出警告信息

性质: Notice的静态方法

参数 类型 描述
msg string 警告信息文本

Notice.info(msg) ⇒ void

控制台输出信息

性质: Notice的静态方法

参数 类型 描述
msg string 信息文本

Notice.getStr(type, msg) ⇒ chalk

获取各种颜色的字体

性质: Notice的静态方法

参数 类型 描述
type ChalkType chalk类型
msg string 文本

Notice.getBoldStr(type, msg) ⇒ chalk

获取各种颜色的粗体字体

性质: Notice的静态方法

参数 类型 描述
type ChalkType chalk类型
msg string 文本

nodeUtils.NpmUtils

npm工具集合

性质: nodeUtils的静态class

NpmUtils.getRegistry() ⇒ string

获取当前项目的npm镜像地址

性质: NpmUtils的静态方法

NpmUtils.getPackageInfo(packageName, [version]) ⇒ Promise

获取npm包的所有版本的所有信息

性质: NpmUtils的静态方法

参数 类型 描述
packageName string 包名
[version] string 版本或tag

NpmUtils.getPackageInfoWithVersion(packageName, [version]) ⇒ Promise

获取指定版本包信息

性质: NpmUtils的静态方法 返回值: Promise - 对应版本包信息

参数 类型 默认值 描述
packageName string 包名
[version] string "latest" 版本或者版本tag

NpmUtils.downloadPackage(options) ⇒ string

下载npm包到本地

性质: NpmUtils的静态方法 返回值: string - 包下载的本地路径

参数 类型 描述
options object 下载配置
options.outputDir string 输出目录
options.packageName string 包名
[options.version] string 版本或者版本tag
[options.autoInstall] boolean | InstallOption 自动下载npm包依赖或者自动下载配置

InstallOption : object

下载配置

性质: downloadPackage的类型声明

属性

属性 类型 默认值 描述
[prod] boolean true 是否只下载生产依赖

nodeUtils.PresetUtils

支持presets预设的配置生成工具

性质: nodeUtils的静态class

Config : object

支持preset的配置对象

性质: PresetUtils的类型声明

属性

属性 类型 描述
presets Array.<Config> 预设配置数组
modify ConfigModify 将默认配置和preset合并后生成的config再次处理的钩子

ConfigModify ⇒ Config

性质: PresetUtils的类型声明

参数 类型 描述
config Config 将默认配置和preset合并后生成的config

PresetUtils.getDeepPreset(config) ⇒ Promise.<Array.<Config>>

递归获取配置对象presets数组,返回一维数组

性质: PresetUtils的静态方法

参数 类型 描述
config Config 配置对象

PresetUtils.getDeepPresetMerge(config) ⇒ Config

递归获取配置对象presets数组,并使用merge合并

性质: PresetUtils的静态方法

参数 类型 描述
config Config 配置对象

PresetUtils.getDeepPresetMergeAndModify(config) ⇒ Config

递归获取配置对象presets数组,并使用merge合并,最后调用config.modify函数

性质: PresetUtils的静态方法

参数 类型 描述
config Config 配置对象

命令行使用文档

Usage: agds-gc-has-msg [options]

判断git commit命令是否传入-m参数

Options:
  -v,--version  查看版本号
  -h, --help    查看帮助信息

配合git hooks【prepare-commit-msg】和【commitizen】使用,避免git commit已经传入-m参数时调用commitizen界面

文档查看:git@gitee.com:agile-development-system/node-utils
@agds/node-utils@1.0.16 /Users/jinyang/code/ads/node-utils/node_modules/@agds/node-utils

许可证

MIT License Copyright (c) 2021 锦阳

请维护者喝杯咖啡

加入钉钉群讨论或加入开发

Package Sidebar

Install

npm i @agds/node-utils

Weekly Downloads

2

Version

1.0.18

License

MIT

Unpacked Size

119 kB

Total Files

43

Last publish

Collaborators

  • chujunyang