Last active
December 3, 2018 21:19
-
-
Save doug2k1/a58032866d1cfee32375c74aca46d9e2 to your computer and use it in GitHub Desktop.
Static site generator in Node.js - https://medium.com/douglas-matoso-english/build-static-site-generator-nodejs-8969ebe34b22
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fse = require('fs-extra') | |
const path = require('path') | |
const { promisify } = require('util') | |
const ejsRenderFile = promisify(require('ejs').renderFile) | |
const globP = promisify(require('glob')) | |
const config = require('../site.config') | |
const srcPath = './src' | |
const distPath = './public' | |
// clear destination folder | |
fse.emptyDirSync(distPath) | |
// copy assets folder | |
fse.copy(`${srcPath}/assets`, `${distPath}/assets`) | |
// read page templates | |
globP('**/*.ejs', { cwd: `${srcPath}/pages` }) | |
.then((files) => { | |
files.forEach((file) => { | |
const fileData = path.parse(file) | |
const destPath = path.join(distPath, fileData.dir) | |
// create destination directory | |
fse.mkdirs(destPath) | |
.then(() => { | |
// render page | |
return ejsRenderFile(`${srcPath}/pages/${file}`, Object.assign({}, config)) | |
}) | |
.then((pageContents) => { | |
// render layout with page contents | |
return ejsRenderFile(`${srcPath}/layout.ejs`, Object.assign({}, config, { body: pageContents })) | |
}) | |
.then((layoutContent) => { | |
// save the html file | |
fse.writeFile(`${destPath}/${fileData.name}.html`, layoutContent) | |
}) | |
.catch((err) => { console.error(err) }) | |
}) | |
}) | |
.catch((err) => { console.error(err) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment