Getting the home directory in nodejs

The home directory or user folder in an operating system is a folder for the current user. This folder is then a good place to park any kind of user specific settings or data when making a nodejs application. So then there should be some kind of standard way of getting a path to this folder in a way that will work across different operating systems. With that said there is in the nodejs built in os module, to which there is a method called homedir.

1 - Basic nodejs os home dir example

A basic example of the node os module homedir method would be to just require in the os module, and then call the homedir method of that module. The string value that is returned is then the home or user folder path for the current user that ran the script.

1
2
3
4
5
6
7
let os = require('os'),
dir_home = os.homedir();
console.log(dir_home);
// C:\Users\[username] in Windows
// /home/[username] in Linux

So the os module homedir method can be used in conjunction with other modules and methods for things like checking to see if there is a config file for the current user in the home path, and if not create it.

2 - basic count file example

Now for a not so basic example of how this can be used for something useful. Here I have an example that will create a count.json file in the home path of the current user if it is not there, otherwise it will use what is there. Each time the script is called one is added to a count property and then the json is saved to the file.

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
let os = require('os'),
path = require('path'),
fs = require('fs'),
promisify = require('util').promisify,
readFile = promisify(fs.readFile),
writeFile = promisify(fs.writeFile),
dir_home = os.homedir();
// get user count file
let getUserCount = () => {
let path_count = path.join(dir_home, '.count.json');
return readFile(path_count)
.then((data) => {
try {
return JSON.parse(data);
} catch (e) {
return {
count: 0
}
}
})
.catch((e) => {
return {
count: 0
}
});
};
let putUserCount = (obj) => {
let path_count = path.join(dir_home, '.count.json');
return writeFile(path_count, JSON.stringify(obj));
};
getUserCount()
.then((obj) => {
console.log(obj.count);
obj.count += 1;
return putUserCount(obj);
});

In a read example something not all to different from that can be used to test for and then write or update a config file of some kind for an actually project of some kind.