1

I am using fs.unlinkSync() method in a Node.js script, in order to remove a file located in Appdata directory.

Best practice of locating the Appdata dir is specifying a path using %appdata%, so in my code:

var filePath = '%appdata%/some/path/file.ext';
fs.unlinkSync(filePath);

The problem is an error is returned, indicating bad path, because it's trying to locate something like:

C:\my\project\%appdata%\some\path\file.ext

Which obviously doesn't exist.

So I'm looking for the best method to resolve %appdata% into C:\Users\user\AppData\Roaming.

Hopefully I can do something along the lines of:

var filePath = resolveToAbsolutePath('%appdata%/some/path/file.ext');
fs.unlinkSync(filePath);

Any kind of help is appreciated.

Notes:

  1. Nope, the issue is unrelated to using forward slashes instead of backslashes.
  2. This is different than using environment variables, as I get the paths externally, and I need to be able to resolve % paths as well. I'm interested in generalising the solution, rather than manually replacing paths with environment variable data.
Selfish
  • 6,023
  • 4
  • 44
  • 63
  • Possible duplicate of [How to read environment variable in Node.js](http://stackoverflow.com/questions/4870328/how-to-read-environment-variable-in-node-js) – Patrick Evans Oct 08 '15 at 12:31
  • Not really a duplicate, as I'm not looking to manually replace a known string with a known variable. I'm looking to resolve any path into it's full, absolute version. The question linked is suggesting manually replacing known variables. – Selfish Oct 08 '15 at 13:19

1 Answers1

5

You can resolve it using a function that will resolve the path:

function resolveToAbsolutePath(path) {
    return path.replace(/%([^%]+)%/g, function(_, key) {
        return process.env[key];
    });
}
resolveToAbsolutePath('%LOCALAPPDATA%\\Google\\Chrome\\Application');
dcohenb
  • 2,099
  • 1
  • 17
  • 34