nodejs有用的工具&代码

907 阅读1分钟

1. 守护进程管理工具 pm2

PM2 是一个带有负载均衡功能的 Node 应用的进程管理器。可以守护进程的形式启动服务,不会随着终端关闭而停止服务。

详细介绍:PM2 使用介绍

  • 简单用法
$ npm install pm2 -g     # 命令行安装 pm2 
$ pm2 start app.js -i 4  # 后台运行pm2,启动4个app.js 
                         # 也可以把'max' 参数传递给 start
                         # 正确的进程数目依赖于Cpu的核心数目
$ pm2 start app.js --name my-api # 命名进程
$ pm2 list               # 显示所有进程状态
$ pm2 monit              # 监视所有进程
$ pm2 logs               # 显示所有进程日志
$ pm2 stop all           # 停止所有进程
$ pm2 restart all        # 重启所有进程
$ pm2 reload all         # 0 秒停机重载进程 (用于 NETWORKED 进程)
$ pm2 stop 0             # 停止指定的进程
$ pm2 restart 0          # 重启指定的进程
$ pm2 startup            # 产生 init 脚本 保持进程活着
$ pm2 web                # 运行健壮的 computer API endpoint (http://localhost:9615)
$ pm2 delete 0           # 杀死指定的进程
$ pm2 delete all         # 杀死全部进程

2. 非递归搜索和处理树的节点

// 非递归搜索和处理节点
function search(tree, callback) {
    if (callback(tree, null) === true) {
        return current;
    };
    let array = [tree];
    for (let i = 0; i < array.length; i++) {
        const current = array[i];
        if (current.children && current.children.length > 0) {
            for (let j = 0; j < current.children.length; j++) {
            	const child = current.children[j];
                if (callback(child, current) === true) {
                    return current;
                };
            	array.push(child);
            }
        }
    }
    return null;
}

const tree = {
    id: '1',
    children: [
        {
            text: '子节点-11',
            id: '11',
            children: [
                {
                    text: '子节点-111',
                    id: '111'
                },
                {
                    text: '子节点-112',
                    id: '112'
                }
            ]
        },
        {
            text: '子节点-12',
            id: '12'
        },
        {
            text: '子节点-13',
            id: '13',
            children: [
                {
                    text: '子节点-131',
                    id: '131'
                },
                {
                    text: '子节点-132',
                    id: '132'
                },
                {
                    text: '子节点-133',
                    id: '133'
                },
                {
                    text: '子节点-134',
                    id: '134'
                },
                {
                    text: '子节点-135',
                    id: '135'
                }
            ]
        },
    ]
};
const result = search(tree, (node, parent) => {
	// 在这里处理node...
    console.log(node.id);
    // 如果返回true则终止搜索
    return node.id === '13';
});
console.log('search result:', result);

3. 汉字拼音转换工具

  • 安装
npm install pinyin
  • 使用
var pinyin = require("pinyin");
 
console.log(pinyin("中心"));    // [ [ 'zhōng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {
  	heteronym: true               // 启用多音字模式
}));                            // [ [ 'zhōng', 'zhòng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {
    heteronym: true,              // 启用多音字模式
    segment: true                 // 启用分词,以解决多音字问题。
}));                            // [ [ 'zhōng' ], [ 'xīn' ] ]
console.log(pinyin("中心", {
    style: pinyin.STYLE_INITIALS, // 设置拼音风格
    heteronym: true
}));                            // [ [ 'zh' ], [ 'x' ] ]
`

4. 打印本地当前目录结构

  • 安装
npm install -g treer
  • 使用
treer # lunux可能是tree命令
# 结果:
src
├─.DS_Store
├─App.vue
├─main.js
├─router
|   └index.js
├─components
|     ├─A.vue
|     ├─HelloWorld.vue
├─assets
|   └logo.png

5. 格式化时间

/**
* 格式化时间
* @method formatTime
* @param {Date} date 格式
* @param {String} formatStr 格式
* @return {String} fmt 格式化字符串
*/
function formatTime(date, formatStr) {
    function format(date, t) {
        var date = new Date(date);
        var o = {
            'M+': date.getMonth() + 1,                 // 月份
            'd+': date.getDate(),                    // 日
            'h+': date.getHours(),                   // 小时
            'm+': date.getMinutes(),                 // 分
            's+': date.getSeconds(),                 // 秒
            'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
            S: date.getMilliseconds()             // 毫秒
        };
        if (/(y+)/.test(t)) {
            t = t.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp('(' + k + ')').test(t)) {
                t = t.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
            }
        }
        return t;
    }
    if (typeof date === 'undefind') {
        throw new Error('the param of function formatTime() can\'t be undefined');
    }
    if (typeof date === 'number') {
        if (typeof formatStr === 'string') {
            return format(date, formatStr);
        }
        return format(date, 'yyyy-MM-dd hh:mm:ss');

    }
    if (typeof date === 'string') {
        date = (new Date(date)).getTime();
        if (typeof formatStr === 'string') {
            return format(date, formatStr);
        }
        return format(date, 'yyyy-MM-dd hh:mm:ss');

    }
    if (Object.prototype.toString.call(date) === '[object Date]') {
        date = date.getTime();
        if (typeof formatStr === 'string') {
            return format(date, formatStr);
        }
        return format(date, 'yyyy-MM-dd hh:mm:ss');

    }
}

6. promise封装fs文件操作方法

作者:alanyf
链接:juejin.cn/post/687031…
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

const fs = require('fs');
const util = require('util');
/**
 * 将nodejs的fs模块的异步操作变为promise模式
 */
function FsAsync(){
    const prototype = this.constructor.prototype;
    const isFun = (e) => Object.prototype.toString.call(e) === '[object Function]';
	const isSync = (s) => s.indexOf('Sync') !== -1 || s.indexOf('sync') !== -1 ;
	for(let p in fs){
		const prop = fs[p];
		if(isFun(prop)){
            prototype[p] = isSync(prop.name) ? prop : util.promisify(prop);
		}
	}
}
module.exports = new FsAsync();

7. nodejs获取本地文件目录

function readFileList(folderPath, filesList = []) {
    folderPath = folderPath + '/';
    const files = fs.readdirSync(folderPath);
    for (const item of files) {
        const stat = fs.statSync(folderPath + item);
        if (stat.isDirectory()) {
            readFileList(folderPath + item, filesList)
        } else {
            const obj = {};
            obj.path = folderPath;
            obj.filename = item
            filesList.push(obj);
        }
    }
    return filesList;
}

8. 命令行参数解析工具

  1. minimist

解析nodejs命令行参数的小工具,将process.argv中的参数解析为对象。

github: github.com/substack/mi…
用法:
node test.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz

test.js

const minimist = require('minimist');
const args = minimist(process.argv.slice(2));
console.log(argv);
// argv log
{
    _: [ 'foo', 'bar', 'baz' ],
    x: 3,
    y: 4,
    n: 5,
    a: true,
    b: true,
    c: true,
    beep: 'boop'
}
  1. commander

用来构建命令行程序的强大工具。

github: github.com/tj/commande…

program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');

program.parse(process.argv);

if (program.debug) console.log(program.opts());
console.log('pizza details:');
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(`- ${program.pizzaType}`);
// result
/*
  $ pizza-options -d
  { debug: true, small: undefined, pizzaType: undefined }
  pizza details:
  $ pizza-options -p
  error: option '-p, --pizza-type <type>' argument missing
  $ pizza-options -ds -p vegetarian
  { debug: true, small: true, pizzaType: 'vegetarian' }
  pizza details:
   small pizza size
   vegetarian
  $ pizza-options --pizza-type=cheese
  pizza details:
   cheese
*/

相关文章:

9. nodejs操作excel文件

记录nodejs读写excel文件方法。

  • 安装
npm install node-xlsx --save
  • 读取 excel 文件为 json
const xlsx = require('node-xlsx');

const sheets = xlsx.parse('./data.xlsx');
console.log(sheets);
  • json 数据写入为 excel 文件
const fs = require('fs');
const xlsx = require('node-xlsx');

const jsonData = [
    {
        name: '计划表',
        data: [
            ['day 1', 'day 2', 'day 2',],
            ['起床', '起床', '起床',],
            ['吃饭', '吃饭', '吃饭',],
            ['上班', '上班', '上班',],
            ['睡觉', '睡觉', '睡觉',],
        ],
    }
]
const buffer = xlsx.build(jsonData);

// 写入excel文件
fs.writeFile('data_copy.xlsx', buffer, err => {
    if (err) {
        console.log('Write failed: ' + err);
        return;
    }
    console.log('Write completed.');
});