node.jsfs

ENOENT error when using fs.writeFile


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'

Solution

  • 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");
    });