Node Read File From %appdata%
Asked Answered
A

1

7

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?

Atkinson answered 14/8, 2015 at 14:12 Comment(0)
P
17

You have to get the value from process.env instead:

fileData = fs.readFileSync(process.env.APPDATA + '/folder/file.txt',{encoding:'utf8'});
Panada answered 14/8, 2015 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.