I am running node and I want to read a file from the %appdata% folder and I would rather not hard-code that path.
This is basically what I have so far:
//...require(some things)
var fs = require('fs');
var fileData;
try{
fileData = fs.readFileSync('%appdata%/folder/file.txt',{encoding:'utf8'});
}
catch(e){
console.log(e);
fileData = 42; //default value
}
//... app.get(some things)
//... app.listen
When I run this, I get the message:
{ [Error: ENOENT, no such file or directory 'C:\projectdirectory\%appdata%\folder\file.txt']
errno: -4058,
code: 'ENOENT',
path: 'C:\projectdirectory\%appdata%\folder\file.txt',
syscall: 'open' }
How do I get it to recognize the %appdata% variable?
You have to get the value from process.env
instead:
fileData = fs.readFileSync(process.env.APPDATA + '/folder/file.txt',{encoding:'utf8'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With