Skip to content

Commit

Permalink
feat: 完成md转换至docx部分逻辑,并实现命令行功能的封装
Browse files Browse the repository at this point in the history
  • Loading branch information
lpreterite committed Feb 23, 2023
1 parent 14fe838 commit d666221
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 81 deletions.
File renamed without changes
2 changes: 1 addition & 1 deletion assets/test.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
网页布局(layout)是 CSS 的一个重点应用。<br />![](../assets/devops.png)
网页布局(layout)是 CSS 的一个重点应用。<br />![](imgs/devops.png)

它可能取5个值,具体对齐方式与轴的方向有关。下面假设主轴为从左到右。

Expand Down
23 changes: 7 additions & 16 deletions src/bin/md2docx
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
#!/usr/bin/env node

const pkg = require("../../package.json");
const path = require("path")
const { Command } = require('commander');
const program = new Command();
const pkg = require("../../package.json");
const md2docx = require('../main');

program
.name("md2docx")
.description(pkg.description)
.version(pkg.version, '-v, --version', `version`)
// .option('')
.argument('<htmlFile>', 'html file')
.action((htmlFile)=>{
.option('-o, --outputDir <string>', 'output path')
.argument('<string>', 'Markdown File')
.action((mdPath)=>{
const opts = program.opts();

md2docx.generate(path.resolve(process.cwd(),mdPath), path.resolve(process.cwd(),opts.outputDir))
})


// program.command('split')
// .description('Split a string into substrings and display as an array')
// .argument('<string>', 'string to split')
// .option('--first', 'display just the first substring')
// .option('-s, --separator <char>', 'separator character', ',')
// .action((str, options) => {
// const limit = options.first ? 1 : undefined;
// console.log(str.split(options.separator, limit));
// });

program.parse();
83 changes: 21 additions & 62 deletions src/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,56 +3,10 @@ const fs = require('fs');
const JSZip = require('jszip');
const marked = require('marked');
const glob = require("glob")
// const internal = require('./internal');

const toDocx = require('./toDocx')

// https://stackoverflow.com/questions/12752622/require-file-as-string
// require.extensions['.html'] = function (module, filename) {
// module.exports = fs.readFileSync(filename, 'utf8');
// };

const outputDir = path.resolve(__dirname, '../assets')
function outputTo(filename, data, type = 'text') {
const types = { 'text': 'txt', 'html': 'html', 'json': 'json' }
const extname = types[type]
return fs.writeFileSync(path.resolve(outputDir, `${filename}.${extname}`), template(filename, data, type))
}

function template(filename, data, type='text'){
if(type === 'html'){
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div>
${data}
</div>
</body>
</html>`
}
if(type === 'json'){
return `{
"title": "${filename}",
"content": "${data.replace(/\"/ig,'\\"')}"
}`
}

return data
}

function asBlob(html, options) {
var zip;
zip = new JSZip();
internal.addFiles(zip, html, options);
return internal.generateDocument(zip);
}

const pwd = path.resolve(__dirname, "../assets/")

glob('assets/*.md', function (err, files) {
files.forEach(file => {
fs.readFile(file, 'utf8', (err, markContent) => {
Expand All @@ -63,30 +17,35 @@ glob('assets/*.md', function (err, files) {
const filename = path.basename(_path, path.extname(_path))
let htmlStr = marked.parse(markContent)
const filePath = `./dist/${filename}.docx`;
outputTo(filename, htmlStr, 'html')
// outputTo(filename, htmlStr, 'html')

fs.writeFile(filePath, asBlob(template(filename, htmlStr, 'text'), { pwd }), (error) => {
if (error) {
console.log('Docx file creation failed');
return;
}
console.log('Docx file created successfully');
});
const pwd = path.resolve(__dirname, "../assets/")
toDocx.generate(filePath, htmlStr, { pwd })
}
})
})
})

const pwd = path.resolve(__dirname, "../assets/")
const html = fs.readFileSync("./assets/example.html",'utf8')
toDocx.generate('./dist/example.docx', html, { pwd })

// const html = require("../assets/example.html");

// fs.writeFile(filePath, asBlob(html, { pwd }), (error) => {
// if (error) {
// console.log('Docx file creation failed');
// return;
// }
// console.log('Docx file created successfully');
// });
function MD2Docx(options={}){
function generate(input, output, {pwd,encoding="utf8"}={}){
const filename = path.basename(input, path.extname(input))
pwd = pwd ? pwd : path.dirname(output)

const mdSource = fs.readFileSync(input, encoding)
const htmlSource = marked.parse(mdSource)

toDocx.generate('./dist/example.docx', htmlSource, { pwd })
}

return {
generate
}
}

const factory = (options) => new MD2Docx(options);
module.exports = module.exports.default = factory()
28 changes: 27 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1 +1,27 @@
import "./example"
const path = require("path")
const fs = require('fs')
const marked = require('marked')
const toDocx = require('./toDocx')

function MD2Docx(options={}){
function generate(input, output, {pwd,encoding="utf8"}={}){
const filename = path.basename(input, path.extname(input))
const outputDir = output ? (fs.lstatSync(output).isDirectory()?output:path.dirname(output)) : path.dirname(input)
pwd = pwd ? pwd : path.dirname(input)
output = path.resolve(outputDir, `${filename}.docx`)

// console.log("MD2Docx: %s | %s | %s", input,output,outputDir)

const mdSource = fs.readFileSync(input, encoding)
const htmlSource = marked.parse(mdSource)

toDocx.generate(output, htmlSource, { pwd })
}

return {
generate
}
}

const factory = (options) => new MD2Docx(options);
module.exports = module.exports.default = factory()
1 change: 0 additions & 1 deletion src/toDocx.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,3 @@ function toDocx(options={}){

const factory = (options) => new toDocx(options);
module.exports = module.exports.default = factory()
module.exports.Constructor = toDocx

0 comments on commit d666221

Please sign in to comment.