I know, it is meant as script, but in
|
var jsonData = fs.readFileSync('_site/_data/properties.json'); |
you're calling code synchronously. A better way would be to put the logic inside a
function
and call it afterwards.
By using es6-promisify you could turn fs.readFile
into a Promise-based API. By using an async function
you could then use await
to read the file.
The code could look akin to this:
const defaultFilePath = '_site/_data/properties.json';
let outputFileName = 'rename-me';
async function makeTemplate () {
const properties = await readAsJson(defaultFilePath);
if (!properties.message) {
return writeFile(properties);
} else {
console.log(properties.message);
}
}
async function readAsJson (filePath) {
const jsonData = await fs.readFile(filePath, 'utf8');
return = JSON.parse(jsonData)[0]; // This could potentially fail!
}
function writeFile (properties) {
const output = computeOutput(properties);
outputFileName = getOutputFileName(properties);
try {
return fs.writeFile(outputFileName, output, 'utf8');
} catch (reason) {
console.error('An error occured while writing JSON Object to file.');
return console.error(reason);
}
}
function computeOutput (properties) {
const frontmatter = yaml.safeDump(properties);
return `---\n${yamlStr}\n---`;
}
function getOutputFileName (properties) {
return `_site/houses-for-sale/${properties.websiteLink}.md`
}
makeTemplate();