我試圖在我的 API 中將本地 md 檔案轉換為 json,但出現語法錯誤。
問題似乎是,當我讀取檔案并將其存盤為字串變數時,它在沒有 md2json 作業所需的新行的情況下存盤。當我控制臺記錄變數時,它會逐行列印,看起來就像 md 檔案一樣,但我無法轉換它。當我將它作為回應發送并列印在我的頁面上時,它會列印:
# Air ## The second largest heading ###### The smallest heading
但是原始的 md 檔案看起來是這樣的:
# Air
## The second largest heading
###### The smallest heading
這是我試過的:
const md2json = require('md-2-json');
const fs = require('fs');
router.get('/page', (req, res) => {
let content = fs.readFileSync('directory/file.md','utf8')
console.log(content)
res.send(content)
})
有什么辦法可以做到這一點,還是有其他更好的方法來做到這一點?我看到了一些關于 XMLHttpRequest 的帖子,但并沒有真正讓它發揮作用。
//* 編輯:我現在看到我忘了包括轉換;這是使用 md2json 時的樣子:
router.get('/page', (req, res) => {
let content = fs.readFileSync('directory/file.md','utf8')
console.log(content)
let newContent = md2json.parse(content)
console.log(newContent)
res.send(newContent)
})
//* 編輯 2:缺少 \n 似乎不是問題所在,因為它有效:
let mdInput = `# Air ## The second largest heading ###### The smallest heading`
router.get('/page', (req, res) => {
let newContent = md2json.parse(mdInput)
console.log(newContent)
res.send(newContent)
但這不是:
let mdInput = `
# Air
## The second largest heading
##### The smallest heading
`
router.get('/page', (req, res) => {
let newContent = md2json.parse(mdInput)
console.log(newContent)
res.send(newContent)
uj5u.com熱心網友回復:
我明白了:這是因為這個庫似乎只允許 h(n) 存在于 h(n-1) 中,所以 h6 不能直接存在于 h2 中,所以這應該可以解決你的問題:
# Air
## The second largest heading
### The third largest heading
#### The fourth largest heading
##### The second smallest heading
###### The smallest heading
const fs = require('fs');
router.get('/page', (req, res) => {
const content = fs.readFileSync('directory/file.md','utf8').toString()
let newContent = md2json.parse(content)
res.end(`<!DOCTYPE html><html><head></head><body>${ newContent }</body></html>`)
})
uj5u.com熱心網友回復:
您的頁面在一行中列印所有內容,因為 html\n默認情況下會忽略為換行符
# Air
## The second largest heading
###### The smallest heading
你必須用pre標簽包裹你的文字
<pre>
# Air
## The second largest heading
###### The smallest heading
</pre>
您還可以使用white-space: precss 屬性或替換\n為<br>
uj5u.com熱心網友回復:
也許你需要用一點 html 來發送它:
const md2json = require('md-2-json');
const fs = require('fs');
router.get('/page', (req, res) => {
const content = fs.readFileSync('directory/file.md','utf8').toString()
let newContent = md2json.parse(content)
res.end(`<!DOCTYPE html><html><head></head><body>${ newContent }</body></html>`)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534462.html
