
Security News
The AI Industry Is Betting on Open Weights
An open letter signed by 50 companies, from NVIDIA and Microsoft to Mistral and Hugging Face, urges Washington not to restrict open weight AI.
func-node-lib
Advanced tools
关于node公共方法工具类
npm install func-node-lib
该库包含以下主要功能模块:
// 方式一: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;
文件操作模块提供了文件和目录的基本操作功能。
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> - 操作结果对象命令行工具模块提供了执行命令行命令的功能。
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}>> - 包含命令执行结果的 Promiseconst 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时间处理模块提供了基于 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');
}
FAQs
关于node公共方法工具类
We found that func-node-lib demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
An open letter signed by 50 companies, from NVIDIA and Microsoft to Mistral and Hugging Face, urges Washington not to restrict open weight AI.

Security News
/Research
A fake corepack.org site is impersonating the Node.js tool and delivers an infostealer and proxyware to developers who download it.

Research
/Security News
A large-scale campaign abused GitHub Actions in compromised repositories to exploit CVE-2026-41940 in cPanel and WHM and steal server credentials.