-
Notifications
You must be signed in to change notification settings - Fork 0
/
yamlFs.js
43 lines (37 loc) · 1.29 KB
/
yamlFs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const YamlFileMetaData = require('./yamlFileMetaData.js');
const postHead = /---((.|\n)*?)---/;
module.exports = class YamlFs {
getMetaDataForFile (filePath) {
try {
let content = fs.readFileSync(filePath, 'utf8');
let match = postHead.exec(content);
let headContent = match[1]
return new YamlFileMetaData(filePath,
yaml.safeLoad(headContent),
headContent,
content);
} catch (e) {
console.log(`There was a problem reading post metadata for: ${filePath}`);
console.log(e);
}
}
getMetaDataForFiles (dirPath) {
return new Promise((res, rej) => {
fs.readdir( dirPath, ( err, files ) => {
if( err ) {
rej(err);
} else {
res(files.map(file => this.getMetaDataForFile(path.join(dirPath, file))))
}
});
});
}
writeFile (fileMetaData) {
let newHeadContent = yaml.safeDump(fileMetaData.yamlProperties);
let newArticleContent = fileMetaData.content.replace(fileMetaData.headContent, `\n${newHeadContent}\n`);
fs.writeFileSync(fileMetaData.filePath, newArticleContent);
}
}