ENOENT error when using fs.writeFile

24,415

Solution 1

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

Solution 2

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.

Share:
24,415
Tom
Author by

Tom

I'm exclusively looking for remote part-time (3 days a week) full stack development work in javascript. Happy to work for employers remotely anywhere in the world.

Updated on July 09, 2022

Comments

  • Tom
    Tom almost 2 years

    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'
    
  • Terra Ashley
    Terra Ashley almost 8 years
    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.
  • retr0
    retr0 over 5 years
    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