使用nodejs输出著作权申请所需的word版源码

使用nodejs输出著作权申请所需的word版源码

背景

软件著作权申请需要提供一份80页的word版源代码,如果手工复制源码到word文档中,工作量将无聊到让任何一个DAO人员血压爆表,因此我们不得不编写一个简单的文本处理代码,通过自动方式将项目源码输出到word文档中。

实现逻辑

指定一个代码目录,通过递归扫描该目录及其所有子级目录下的文件(可指定文件类型),然后按行读取文件中的代码,输出到word文档中。

实现代码

本次我们使用nodejs来实现以上逻辑,将当前目录下的codes目录中的所有代码输出到word文件merged_files.docx中。

javascript 复制代码
const fs = require('fs-extra');
const path = require('path');
const readline = require('readline');
const docx = require("docx");

const graphs = [];

async function readFileContent(filePath) {
  return fs.readFile(filePath, 'utf8');
}

function createParagraph(text) {
  const paragraph = new docx.Paragraph({ children: [new docx.TextRun(text)] });
  graphs.push(paragraph);
}

function readLineContent(fullPath) {
  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(fullPath);
    const rl = readline.createInterface({
      input: readStream,
      crlfDelay: Infinity
    });
  
    rl.on('line', (line) => {
      // console.log('Line from file:', line);
      createParagraph(line);
    });

    rl.on('close', () => {
      resolve();
    });
  });
}


async function convertDirectoryToDocx(directoryPath) {
  try {
    const files = await fs.readdir(directoryPath, { withFileTypes: true });

    for (const file of files) {
      const fullPath = path.join(directoryPath, file.name);
      if (file.isDirectory()) {
        await convertDirectoryToDocx(fullPath); // 递归处理子目录
      } else {
        await readLineContent(fullPath);
        // 添加空行
        createParagraph('                 ');
        createParagraph('                 ');
        createParagraph('                 ');
        createParagraph('                 ');
        createParagraph('                 ');
      }
    }

  } catch (err) {
    console.error(`读取目录出错: ${directoryPath}`, err);
  }
}

async function createDocx() {
  const inputDir = './codes'; // 输入目录路径

  await convertDirectoryToDocx(inputDir);
  
  const doc = new docx.Document({
    sections: [
        {
            properties: {},
            children: graphs,
        },
    ],
  });
  
  const outputDocx = './merged_files.docx'; // 输出的.docx文件路径
  
  docx.Packer.toBuffer(doc).then((buffer) => {
    fs.writeFileSync(outputDocx, buffer);
    console.log(`文件已合并至: ${outputDocx}`);
  });
}


createDocx();
相关推荐
basketball61627 分钟前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
宁酱醇35 分钟前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
啊吧怪不啊吧42 分钟前
Linux常见指令介绍下(入门级)
linux·开发语言·centos
谷晓光43 分钟前
Python 中 `r` 前缀:字符串处理的“防转义利器”
开发语言·python
李剑一44 分钟前
写一个vitepress新建文章脚本,自动化创建链接,别再手写了!
前端·node.js·vitepress
Tiger Z1 小时前
R 语言科研绘图第 41 期 --- 桑基图-基础
开发语言·r语言·贴图
chuxinweihui1 小时前
数据结构——二叉树,堆
c语言·开发语言·数据结构·学习·算法·链表
陈大大陈1 小时前
基于 C++ 的用户认证系统开发:从注册登录到Redis 缓存优化
java·linux·开发语言·数据结构·c++·算法·缓存
看到我,请让我去学习1 小时前
C语言基础(day0424)
c语言·开发语言·数据结构
studyer_domi1 小时前
Matlab 复合模糊PID
开发语言·matlab