使用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();
相关推荐
虽千万人 吾往矣3 分钟前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
创作小达人5 分钟前
家政服务|基于springBoot的家政服务平台设计与实现(附项目源码+论文+数据库)
开发语言·python
郭二哈8 分钟前
C++——list
开发语言·c++·list
杨荧9 分钟前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
ZPC821015 分钟前
Python使用matplotlib绘制图形大全(曲线图、条形图、饼图等)
开发语言·python·matplotlib
镜花照无眠17 分钟前
Python爬虫使用实例-mdrama
开发语言·爬虫·python
aaasssdddd9628 分钟前
python和c
c语言·开发语言·python
星星法术嗲人42 分钟前
【Java】—— 集合框架:Collections工具类的使用
java·开发语言
黑不溜秋的1 小时前
C++ 语言特性29 - 协程介绍
开发语言·c++
一丝晨光1 小时前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby