UNPKG

albertgao.common-electron

Version:

个人常用的nodejs/electron模块

77 lines (73 loc) 1.86 kB
const Fs = require('fs-extra') let titles = null let path = '' /** * 用于向主进程发送数据 */ function postMsg() { process.send(...arguments) } /** * @param {object | string[]}line0 line */ function handleLine(line0) { if (line0) { if (/array/i.test(Object.prototype.toString.call(line0))) { // 如果是数组,就直接输出就可以了 line0 = line0.map((e) => (e ? `${e}` : '')) Fs.appendFileSync(path, '\n' + line0.join(',')) } else { // 如果是对象 if (!titles) { titles = Object.keys(line0) // 如果还没有分配titles Fs.writeFileSync(path, titles.join(',')) } const line = titles.map((key) => (line0[key] ? line0[key] : '')) // 根据titles顺序变为字符串数组 Fs.appendFileSync(path, '\n' + line.join(',')) // 把一行数据加上 } } } /** * @param {object}root0 传入的msg * @param {string}root0.path 目标路径 * @param {string[]}root0.titles titles * @param {object | string[]}root0.line line * @param {string}root0.id id */ function handleData({ path: path0, titles: titles0, line: line0, // 单行传入 lines: lines0, // 多行传入 id = '' }) { if (path0) { path = path0 // 给定了path之后,搞一个空文件 Fs.ensureFileSync(path0) Fs.writeFileSync(path, '') } if (titles0) { // 如果传入了titles titles = titles0 Fs.writeFileSync(path, titles.join(',')) } if (line0) { // 如果单行传入() handleLine(line0) line0 = null // 释放内存 } if (lines0) { // 如果多行传入 for (let line1 of lines0) { handleLine(line1) line1 = null // 释放内存 } lines0 = null // 释放内存 } postMsg({ complete: true, id }) } /** * 用于接收主进程发来的数据 */ process.on('message', handleData)