21

Trying to write to a file using fs.writeFile into a sibling directory. This works fine when using Sitemap.xml into the same directory, but not with the relative path. The public directory exists and it gives the same error whether or not Sitemap.xml exists.

Relevant dir structure:

/public
   Sitemap.xml
   app files
/create-sitemap
    index.js - file containing code below
app.js

fs.write('../public/Sitemap.xml', data.toString(), function(err) {
    if (err) throw err;
    console.log("Wrote sitemap to XML");
});


Toms-MacBook-Pro:moviehunter tomchambers$ node create-sitemap/index.js

/Users/tomchambers/projects/project/create-sitemap/index.js:88
        if (err) throw err;
                       ^
Error: ENOENT, open '../public/Sitemap.xml'
Tom
  • 1,546
  • 2
  • 20
  • 42

2 Answers2

34

When you use relative paths in node, they're related to the node process. So, if you run your script like node create-sitemap/index.js from the /Users/tomchambers/projects/project/ directory, it'll look for the /Users/tomchambers/projects/public/Sitemap.xml file, which doesn't exist.

In your case, you could use the __dirname global variable, that returns, as the docs say:

The name of the directory that the currently executing script resides in.

So your code should looks like this:

var path = require('path');

fs.write(path.join(__dirname, '../public/Sitemap.xml'), data.toString(), function(err) {
  if (err) throw err;
  console.log("Wrote sitemap to XML");
});
Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
  • 1
    I recommend using `process.chdir()` to change your app's working directory to __dirname (or a more useful path, if for example using asar). This will allow you to use relative paths without any extra fuss. – Terra Ashley Aug 16 '16 at 02:40
  • 1
    I was facing this error when I tried to generate `fileName` using `path.join('abc', '.', 'pdf')` which put a `'/'` before and after the `'.'` character. Hope this comment helps somebody – retr0 Mar 08 '19 at 06:55
  • This saved my day. One note is to make sure where you call the path, if you are in a subdirectory make sure to take that in consideration. – Alexander Nicholas Popa Sep 03 '22 at 20:45
9

For me the problem was that the given filename contained unallowed characters on Windows.

Specifically, I tried adding a timestamp to the name e.g. 10:23:11 and the : were not allowed which caused this error.

IceRevenge
  • 1,451
  • 18
  • 33