So now and then I might want to read a file in my hexo working tree that contains data that is needed when generating pages. For example I may have a file in my root name space that contains API access keys that are hidden from git with a .gitignore file. I might be using some API that requires an access key to get data that I used in the build process, so I will want to read that file, and fail gracefully if for some reason it’s not there.
The Promise.
I will want to use a promise, as this is often what is used within hexo, and it is what is needed to do any kind of async thing such as reading a file or making a request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// the first promise I wrote myself
readFile = function (path, filename) {
returnnewPromise(function (resolve, reject) {
fs.readFile(path + filename, 'utf8', function (err, data) {
if (err) {
reject('Error reading file: ' + err);
}
resolve(data);
});
});
};
A simple read file tag
So I might want a tag that I can use to inject data from anywhere in my root namespace into a blogpost.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// read a file from the base dir forward.
hexo.extend.tag.register('mytags_readfile', function (args) {
Here for example I will use it to inject the package.json file from my hexo project.
1
{% mytags_readfile package.json %}
Geting an access key, or token from my apikeys.json file.
With some api’s I must have an access token, or api key of some kind. I would not want to hard code an access key into my source code, and push it to a public reposatory. So I would want to read data from a hidden file to get a key, then use that key to make a request to the api.
To get started with this first I will want a method to get the key from my hidden apikeys.json file. It will make use of the readFile method I just put togeather.
This will make a request with a key that I obtained from apikeys.json thanks to my getKey, readFile, and an httpRequest method I found earlier. All of which is in my-tags.js in my hexo scripts folder.
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var formatRepos = function (content) {
html = '<pre> Here are my repos at github.<br><br>';