基本共有套路
首先是要先把包給發(fā)布出來,前面的教程很明確,基本囊括所有,除了包的具體功能要擴(kuò)展,其他先要干的就是一個(gè)流程:
- 新建文件夾,里面建立package.json文件
終端輸入
npm init -y
傻瓜式操作,注意命名沖突的錯(cuò)誤。
- 新建index.js文件
根據(jù)上次的教程,做成命令工具,index.js開頭有句話:
#!/usr/bin/env node
- package.json的對象里新增一個(gè)屬性:
"bin": {
"mdtohtml": "./index.js"
}
現(xiàn)在想想思路:
我們是要在一個(gè)目錄下輸入命令
mdtohtml file.md out.html
得到一個(gè)file.md文件,讀取,得到字符串,處理字符串,寫入html。
這里有個(gè)問題,現(xiàn)在剛發(fā)布,正在開發(fā),修改代碼就要發(fā)布,再執(zhí)行,,,太麻煩了。
依靠調(diào)用命令的指針原理,調(diào)用的就是下載到本地的/usr/local/lib/node_modules/markdowntoohtml/index.js(mac的),那就在這個(gè)文件上修改,再直接調(diào)用命令測試,直到可以了,然后再把結(jié)果復(fù)制到包的文件里,再發(fā)布。
開始實(shí)現(xiàn)功能
需要從用戶輸入的命令里得到目標(biāo)文件
首先,肯定是輸入了一個(gè)類似a.md的一個(gè)文件名,然后如何得到這個(gè)文件的絕對路徑?
一個(gè)模塊process.argv功能,它可以傳入?yún)?shù)的,這時(shí)候,在index.js寫入console.log(process.argv)測試下,運(yùn)行命令
mdtohtml a.md b.html
數(shù)組啊,第三四項(xiàng)就是我們的參數(shù)啊。
所以傳參就容易了,index.js里輸入
if (process.argv.length < 4) {
console.log('輸入的參數(shù)不對,,,')
} else {
var inputPath = process.argv[2]
var outputPath = process.argv[3]
}
讀文件寫文件
需要nodejs內(nèi)置模塊,index.js寫入
var fs = require('fs')
if (process.argv.length < 4) {
console.log('輸入的參數(shù)不對,,,')
} else {
var inputPath = process.argv[2]
var outputPath = process.argv[3]
fs.readFile(inpath, 'utf8', function(err, str) {
if (err) {
console.log('read failed,,,')
} else {
console.log(str)
fs.writeFile(outpath, result, function(err) {
if (err) {
return console.log('read failed,,,')
} else {
console.log('writed,,,,')
}
})
}
})
}
三個(gè)要處理的問題
- 讀取文件路徑的獲取inpath獲取
引入一個(gè)模塊功能process.cwd(),它是得到了一個(gè)當(dāng)前所在的目錄的路徑,然后再加上inputPath,不就是了嗎?
又有一個(gè)問題了,mac跟win系統(tǒng)的路徑表現(xiàn)不一樣啊,這個(gè)不是問題啊,再引入一個(gè)模塊path,反正是問題的差不多都解決了,
var path = require('path')
inpath 就是path.resolve(process.cwd(),inputPath)
- 同理寫入的文件outpasth類似了:
path.resolve(process.cwd(),outputPath)
- 讀到str數(shù)據(jù)了,要處理成html格式了,也就是上面那一串的里的result,它是什么呢?
需要對應(yīng)的包包,npm上查一下
得到一個(gè)markdown-it的包,看了它的教程,直接先安裝到本地目錄下,然后再index.js寫入
var mdit = require('markdown-it')
var md = new mdit()
result就是 md.render(str)
最終的全部代碼就是
var fs = require('fs')
var path = require('path')
console.log(process.argv)
var mdit = require('markdown-it')
var md = new mdit()
if (process.argv.length < 4) {
console.log('輸入的參數(shù)不對,,,')
} else {
var inputPath = process.argv[2]
var outputPath = process.argv[3]
console.log(process.cwd())
fs.readFile(path.resolve(process.cwd(), inputPath), 'utf8', function(err, str) {
if (err) {
console.log('read failed,,,')
} else {
console.log(str)
var result = md.render(str)
fs.writeFile(path.resolve(process.cwd(), outputPath), result, function(err) {
if (err) {
return console.log('read failed,,,')
} else {
console.log('writed,,,,')
}
})
}
})
}
測試一下
在終端里,a.md所在路徑下,輸入
mdtohtml a.md b.html
結(jié)果: