NodeJS fs.open failing on existing file (not a path issue)

Brandon picture Brandon · Feb 3, 2012 · Viewed 30.8k times · Source

I've been dealing with this for a long time, so any help is much appreciated. So, I'm downloading a file and saving it using PhantomJS and CasperJS. Let me point out that they aren't the issue. The file is downloaded without a problem.

The problem is that NodeJS won't recognize or open the file after it is downloaded. I can't fs.stat, fs.open, etc.. Nothing works.

I'll share the code in a second, but here's the log:

Here: bdTcK6hSdownload.csv

[ '2puzZMeLdownload.csv',
  '2s5ICbKNdownload.csv',
  'bdTcK6hSdownload.csv',
  'izIfagwCdownload.csv' ]

fs.js:230

return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);

Error: ENOENT, no such file or directory './caspertemp/bdTcK6hSdownload.csv'

at Object.openSync (fs.js:230:18)
at Object.processCSV (/Users/Home/dev/node_modules/inviter/index.js:64:29)
at /Users/Home/dev/node_modules/inviter/index.js:36:33
at ChildProcess.exithandler (child_process.js:281:7)
at ChildProcess.emit (events.js:70:17)
at maybeExit (child_process.js:361:16)
at Process.onexit (child_process.js:397:5)

As you can see, I'm printing out the created file name, then printing the contents of the directory and then trying to open the file. As you can see, bdTcK6hSdownload.csv exists in the directory but fails on open.

The simple code snippet is here:

console.log('Here: ' + filename);

filenames = fs.readdirSync('./caspertemp/');
console.log(filenames);

var fd = fs.openSync('./caspertemp/' + filename, 'r');
console.log(fd);

There's a bunch more going on before and after this but none of it matters since this basic function fails. Please help! This has been nagging for weeks.

Answer

Peter Lyons picture Peter Lyons · Feb 4, 2012

My guess is that it's a discrepancy in current working directory. Are you starting the casperJS and node.js processes from the same directory? Do either of them change working directory at runtime? Try something like this, where node's __dirname will give you the directory path of the currently executing .js file

var path = require("path");
var filename = "bdTcK6hSdownload.csv";
var csvPath = path.resolve(path.join(__dirname, "caspertemp", filename));
console.log(csvPath);