🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

func-node-lib

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

func-node-lib

关于node公共方法工具类

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

func-node-lib

关于node公共方法工具类

安装

npm install func-node-lib

功能模块

该库包含以下主要功能模块:

  • 文件操作 - 文件和目录的读取、写入、复制和删除
  • 命令行工具 - 执行命令行命令,支持进度条显示
  • 时间处理 - 基于 dayjs 的时间格式化和计算工具

使用方法

导入方式

// 方式一:ES Module 按模块导入
import { fileUtils, cpUtils, dayjsUtils } from 'func-node-lib';

// 方式二:ES Module 导入整个库
import NLib from 'func-node-lib';
const { file, child, dayjs } = NLib;

// 方式三:CommonJS 按模块导入
const { fileUtils, cpUtils, dayjsUtils } = require('func-node-lib');

// 方式四:CommonJS 导入整个库
const NLib = require('func-node-lib').default;
const { file, child, dayjs } = NLib;

文件操作 (fileUtils)

文件操作模块提供了文件和目录的基本操作功能。

读取文件

const readResult = fileUtils.read_file('path/to/file.txt');
if (readResult.success) {
  console.log('文件内容:', readResult.data);
} else {
  console.error('读取失败:', readResult.message);
}

参数说明:

  • filePath: string - 文件路径

返回值:

  • Result<string> - 包含文件内容的结果对象

写入文件

const writeResult = fileUtils.write_file('path/to/file.txt', '要写入的内容');
if (writeResult.success) {
  console.log(writeResult.message); // 文件为空或不存在,已写入内容
} else {
  console.error('写入失败:', writeResult.message);
}

参数说明:

  • filePath: string - 文件路径
  • content: string - 要写入的内容

返回值:

  • Result<void> - 操作结果对象
  • 如果文件不存在或为空,将写入内容
  • 如果文件存在且非空,将追加内容

复制目录

const copyResult = fileUtils.copy_dir('source/dir', 'target/dir');
if (copyResult.success) {
  console.log(copyResult.message); // 复制成功:source/dir → target/dir
}

参数说明:

  • source: string - 源目录路径
  • target: string - 目标目录路径
  • mode: 'copy' | 'move' - 操作模式,默认为 'copy'

返回值:

  • Result<void> - 操作结果对象

删除文件或目录

const deleteResult = fileUtils.delete_file_or_dir('path/to/delete');
if (deleteResult.success) {
  console.log(deleteResult.message); // 删除成功
}

参数说明:

  • pathStr: string - 要删除的文件或目录路径

返回值:

  • Result<void> - 操作结果对象

命令行工具 (cpUtils)

命令行工具模块提供了执行命令行命令的功能。

执行单个命令

try {
  const result = await cpUtils.exec_command('ls -la', './');
  if (result.success) {
    console.log('命令执行成功:', result.data.stdout);
  } else {
    console.error('命令执行失败:', result.message);
  }
} catch (error) {
  console.error('命令执行异常:', error);
}

参数说明:

  • command: string - 要执行的命令
  • cwd: string - 执行命令的目录

返回值:

  • Promise<Result<{stdout: string, stderr: string}>> - 包含命令执行结果的 Promise

执行多个命令

const commands = [
  'npm install',
  'npm run build',
  'npm run test'
];

const result = await cpUtils.exec_commands(commands, './', { showProgress: true });
if (result.success) {
  console.log(result.message); // 所有命令执行完成
} else {
  console.error('执行失败:', result.message);
}

参数说明:

  • commands: string | string[] - 要执行的命令或命令数组
  • cwd: string - 执行命令的目录
  • options: { showProgress?: boolean } - 选项,是否显示进度条,默认为 true

返回值:

  • Promise<Result<void>> - 包含命令执行结果的 Promise

时间处理 (dayjsUtils)

时间处理模块提供了基于 dayjs 的时间格式化和计算功能。

格式化时间

// 格式化当前时间
console.log(`当前时间: ${dayjsUtils.format_time()}`);
// 输出示例: 当前时间: 2023-07-15 14:30:45

// 格式化指定时间
const date = new Date('2023-07-15T06:30:45Z');
console.log(`指定时间: ${dayjsUtils.format_time(date)}`);
// 输出示例: 指定时间: 2023-07-15 14:30:45

// 自定义格式
console.log(`自定义格式: ${dayjsUtils.format_time(date, 'YYYY年MM月DD日 HH时mm分ss秒')}`);
// 输出示例: 自定义格式: 2023年07月15日 14时30分45秒

参数说明:

  • date?: Date | number | string - 日期对象、时间戳或日期字符串,默认为当前时间
  • format?: string - 格式化模式,默认为 'YYYY-MM-DD HH:mm:ss'
  • tz?: string - 时区,默认为 'Asia/Shanghai'

返回值:

  • string - 格式化后的时间字符串

计算耗时

// 计算两个时间点之间的耗时
const startTime = Date.now();
// 执行一些操作...
setTimeout(() => {
  const endTime = Date.now();
  console.log(`耗时: ${dayjsUtils.calculate_duration(startTime, endTime)}`);
  // 输出示例: 耗时: 1.50s
}, 1500);

参数说明:

  • start_time: Date | number - 开始时间点(Date对象或时间戳)
  • end_time?: Date | number - 结束时间点(Date对象或时间戳),默认为当前时间

返回值:

  • string - 格式化后的耗时字符串

实际应用示例

文件上传场景

async function uploadWithRetry(localPath, remotePath, retries = 2) {
  const uploadStart = Date.now();
  console.log(`📍 上传开始时间: ${dayjsUtils.format_time(uploadStart)}`);

  for (let attempt = 1; attempt <= retries + 1; attempt++) {
    try {
      console.log(`📤 上传第 ${attempt} 次尝试...`);
      // 实际上传逻辑...
      const success = await ssh.putDirectory(localPath, remotePath, {
        recursive: true,
        concurrency: 5
      });
      
      if (success) {
        const uploadEnd = Date.now();
        console.log(`✅ 上传成功`);
        console.log(`📍 上传结束时间: ${dayjsUtils.format_time(uploadEnd)}`);
        console.log(`⏱️ 上传耗时: ${dayjsUtils.calculate_duration(uploadStart, uploadEnd)}`);
        return;
      } else {
        throw new Error('上传返回 false');
      }
    } catch (e) {
      console.error(`❌ 上传失败 (第 ${attempt} 次): ${e.message}`);
      if (attempt > retries) {
        throw new Error('多次上传失败,部署终止');
      }
    }
  }
}

批量执行命令场景

async function deployProject() {
  console.log(`📍 部署开始时间: ${dayjsUtils.format_time()}`);
  const startTime = Date.now();
  
  const deployCommands = [
    'git pull',
    'npm install',
    'npm run build',
    'pm2 restart app'
  ];
  
  const result = await cpUtils.exec_commands(deployCommands, './project', { showProgress: true });
  
  if (result.success) {
    console.log(`✅ 部署成功`);
    console.log(`⏱️ 部署耗时: ${dayjsUtils.calculate_duration(startTime)}`);
  } else {
    console.error(`❌ 部署失败: ${result.message}`);
  }
}

文件处理场景

async function processLogFiles(logDir, outputDir) {
  console.log(`📍 处理开始时间: ${dayjsUtils.format_time()}`);
  const startTime = Date.now();
  
  try {
    // 确保输出目录存在
    const mkdirResult = fileUtils.copy_dir(outputDir, outputDir);
    if (!mkdirResult.success && !mkdirResult.message.includes('已存在')) {
      throw new Error(`创建输出目录失败: ${mkdirResult.message}`);
    }
    
    // 读取日志文件
    const logFiles = fs.readdirSync(logDir).filter(file => file.endsWith('.log'));
    console.log(`找到 ${logFiles.length} 个日志文件`);
    
    // 处理每个日志文件
    for (const logFile of logFiles) {
      const logPath = path.join(logDir, logFile);
      const outputPath = path.join(outputDir, `processed_${logFile}`);
      
      const readResult = fileUtils.read_file(logPath);
      if (!readResult.success) {
        console.error(`读取文件失败: ${logPath}, ${readResult.message}`);
        continue;
      }
      
      // 处理日志内容
      const processedContent = processLogContent(readResult.data);
      
      // 写入处理后的内容
      const writeResult = fileUtils.write_file(outputPath, processedContent);
      if (!writeResult.success) {
        console.error(`写入文件失败: ${outputPath}, ${writeResult.message}`);
      } else {
        console.log(`处理完成: ${logFile} -> ${path.basename(outputPath)}`);
      }
    }
    
    console.log(`✅ 所有文件处理完成`);
    console.log(`⏱️ 总耗时: ${dayjsUtils.calculate_duration(startTime)}`);
  } catch (error) {
    console.error(`❌ 处理失败: ${error.message}`);
  }
}

function processLogContent(content) {
  // 实际的日志处理逻辑
  return content.replace(/ERROR/g, '❌ ERROR')
                .replace(/WARNING/g, '⚠️ WARNING')
                .replace(/INFO/g, 'ℹ️ INFO');
}

Keywords

javascript

FAQs

Package last updated on 15 Aug 2025

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