본문 바로가기
핀테크 서비스 프론트엔드 개발자 취업 완성 2기/학습일지

[TIL] nodejs ( md 파일을 html파일로 바꿔보자!!)

by flyda 2022. 7. 15.

nodejs로 간단한 코딩을 하는 것을 배웠다.! 

nodejs 환경에서 md 파일을 html파일로 변환해서 브라우져에 출력하는 코드를 배웠다!! 

코드는 깃헙에서 볼 수 있다!! 

npm init -y

npm i marked

npm i jsdom

 

독타입이 없으면 브라우저에서 html파일로 해석될 보장이 없음,.!!

 

---
// YAML 

---
# ABC

Hello World!

### fruits

- Apple
- Banana
- Cherry

npm i js-yaml : yaml 포멧을 읽어서 js형태로 바꿀수 있음! 검색어(yaml format to js)

 

npm i nodemon 

  "scripts": {
    "start": "nodemon index.js"
  },

개발 서버? 같은거임!! npm start 하면 계속 볼 수 있음!  위에서 package.json파일에서 고쳐 줘야한다!!

 

 

코드에서 주석 처리한 부분을 중점으로 봐야한다!! 

const fs = require('fs')
const marked = require('marked')
const yaml = require('js-yaml')
const jsdom = require('jsdom')
const { JSDOM } = jsdom

const mdDir = `${__dirname}/markdowns`
const htmlDir = `${__dirname}/html`
const indexHTML = fs.readFileSync(`${__dirname}/index.html`, { encoding: 'utf8' })

if (!fs.existsSync(htmlDir)) {
  fs.mkdirSync(htmlDir)
}

const mds = fs.readdirSync(mdDir)
// mds => ['abc.md', 'xyz.md']
mds.forEach(file => {
  // file => 'abc.md'
  let md = fs.readFileSync(`${mdDir}/${file}`, { encoding: 'utf8' })
  /**
   * md =>
   * `---
    title: ABC(abc)
    description: ABC...
    tags: 
      - a
      - b
      - c
    ---

    # ABC

    Hello world!

    ### Fruits

    - Apple
    - Banana
    - Cherry`
   */
  const headers = getHeaders(md)
  /**
   * headers =>
   * `title: ABC(abc)
    description: ABC...
    tags: 
      - a
      - b
      - c
   */
  md = removeHeaders(md, headers)
  /**
   * md =>
   * `

    # ABC

    Hello world!

    ### Fruits

    - Apple
    - Banana
    - Cherry`
   */
  const { title } = yaml.load(headers)
  // { title: 'ABC(abc)', description: 'ABC...', tags: [ 'a', 'b', 'c' ] }
  const dom = new JSDOM(indexHTML)

  const html = marked.parse(md)
  /**
   * `<h1 id="abc">ABC</h1>
    <p>Hello world!</p>
    <h3 id="fruits">Fruits</h3>
    <ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Cherry</li>
    </ul>`
   */
  dom.window.document.querySelector('title').innerHTML = title
  dom.window.document.body.innerHTML = html

  const filename = file.replace('.md', '.html')
  fs.writeFileSync(`${htmlDir}/${filename}`, dom.serialize())
})

function getHeaders(md) {
  return md.split('---').filter(s => s)[0]
}
function removeHeaders(md, headers) {
  console.log(JSON.stringify(headers))
  return md.replace('---' + headers + '---', '')
}

코드의 흐름을 봐 줘야 한다...!! 강사님이 오늘 배운 코드를 다시 한번 보면서 이해해 보라고 권해주셨다!! 

최종으로 완성한 index.js 코드!! 

const fs = require('fs')
const marked = require('marked')
const yaml = require('js-yaml')
const jsdom = require('jsdom')
const { JSDOM } = jsdom

const mdDir = `${__dirname}/markdowns`
const htmlDir = `${__dirname}/dist`
const indexHTML = fs.readFileSync(`${__dirname}/index.html`, { encoding: 'utf8' })

if (fs.existsSync(htmlDir)) {
  fs.rmdirSync(htmlDir, { recursive: true })
}
fs.mkdirSync(htmlDir)

const mds = fs.readdirSync(mdDir)
mds.forEach(file => {
  let md = fs.readFileSync(`${mdDir}/${file}`, { encoding: 'utf8' })
  const headers = getHeaders(md)
  md = removeHeaders(md, headers)
  const { title } = yaml.load(headers)
  const dom = new JSDOM(indexHTML)

  const html = marked.parse(md)
  dom.window.document.querySelector('title').innerHTML = title
  dom.window.document.body.innerHTML = html

  const filename = file.replace('.md', '')
  fs.mkdirSync(`${htmlDir}/${filename}`)
  fs.writeFileSync(`${htmlDir}/${filename}/index.html`, dom.serialize())
})

function getHeaders(md) {
  return md.split('---').filter(s => s)[0]
}
function removeHeaders(md, headers) {
  return md.replace('---' + headers + '---', '')
}

 

 

수업 끝에는 새로운 프로잭트 시작...! 

본격적으로 백엔드?와 관련된 코딩을 해보기 위해서 프로젝트를 설치하고 수업끝..! 

npm init -y

npm i express cors

 

 

댓글