前提条件:
已经安装好node环境,新建一个项目,再引入包 markdown-it;这时候出现了错误:
npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\dev\\nodejs\\node.exe" "C:\\dev\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "markdownn-it" "--save"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10
npm ERR! code E404
npm ERR! 404 Not found : markdownn-it
npm ERR! 404
npm ERR! 404 'markdownn-it' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! Please include the following file with any support request:
npm ERR! F:\others\XAMPP\htdocs\es6\node\hello\npm-debug.log
F:\others\XAMPP\htdocs\es6\node\hello>npm install markdownn-it --save
npm ERR! Windows_NT 10.0.17134
npm ERR! argv "C:\\dev\\nodejs\\node.exe" "C:\\dev\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "markdownn-it" "--save"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10
npm ERR! code E404
npm ERR! 404 Not found : markdownn-it
npm ERR! 404
npm ERR! 404 'markdownn-it' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! Please include the following file with any support request:
npm ERR! F:\others\XAMPP\htdocs\es6\node\hello\npm-debug.log
最关键错误就是404错误:npm ERR! 404 Not found : markdownn-it然后去百度了一下,才发现我的npm没有安装淘宝镜像,然后我去安装了淘宝镜像:>npm install -g cnpm -registry=https//registry.npm.taobao.org
然后安装成功会出现一堆信息。
- 然后在cmd继续执行
>npm install markdown-it --save
如图这样就好了。
新生成了包:
在项目的总目录下新建一个package.json文件:在cmd下输入命令:F:\others\XAMPP\htdocs\es6\node\hello>npm init -y;直接enter这样机会使用默认信息生成一个json文件:
- 写main.js测试代码:
var md = require('markdown-it')();
var result = md.render('# markdown-it rulezz!');
console.log(result);
- cmd运行js
F:\others\XAMPP\htdocs\es6\node\hello>node .
//打印出结果
<h1>markdown-it rulezz!</h1>
- 新建一个hello.md文件:
里面内容为:里面符号和内容都是有空格的
# 一级标题
## 二级标题
### 三级标题
- 列表信息
+ 二级列表
* 三级列表
- 建立tpl.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>模板页面</title>
</head>
<body>
<%content%>
</body>
</html>
- 新建hello.html文件,用来展示转换后的页面:里面是空白的,可以在tpl.html模板文件里面设置样式。
- 新建main.js文件
//获取markdown文件
const path = require('path');
const fs = require('fs');
const md = require('markdown-it')();
let tplPath = path.join(__dirname, 'tpl.html');//模板文件
let mdPath = path.join(__dirname, 'hello.md');//md文件路径
let targetPath = path.join(__dirname, 'hello.html');//展示页面文件
//获取md文件
fs.readFile(mdPath, 'utf8', (err, data) => {
if(err) return;
//对md文件内容进行转换操作
let result = md.render(data);
//读取模板内容.异步地读取文件的全部内容。
let tpl = fs.readFile(tplPath, 'utf8', (err, tplData) => {
if(err) return;
tplData = tplData.replace('<%content%>', result);
//生成的最终页面写入目标文件
fs.writeFile(targetPath, tplData, (err) => {
console.log('转换完成');
});
});
})
运行后页面如图1:然后展示页面的html文件,hello.html内容会添加如图2: