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'
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With