Node.js file not found
I'm using Node.exe in the following file structure
Node/
node.exe
index.js
/vi开发者_如何转开发ew
index.html
When running the following code:
var html;
fs.readFileSync('/view/index.html', function(err, data) {
if(err){
throw err;
}
html = data;
});
I get the following error:
Error: ENOENT, The system cannot find the file specified. '/view/index.html'
Can you see what's causing the error? I'm quite new to node.js.
Additional information: I'm running Windows 7 64 bit, up to date version of node.exe.
I've found the solution!
When node.exe is run through cmd the default directory for node.exe is user.... that's where I was going wrong, it wa using a different directory to where the node.exe is located.
Few things:
- You should resolved the relative path first to real path and try reading the file.
- Read the file asynchronously to get the callback
- Relative path should be corrected. The "./view/index.html" in my code is the path relative to where you start your node.js engine.
Rough code will be:
// get real path from relative path
fs.realpath('./view/index.html', function(err, resolvedPath) {
// pass the resolved path to read asynchronously
fs.readFile(resolvedPath, function(err, data) {
// assign the variable per your use case
html = data;
})
});
Note that I am using version 4.11 (latest stable version)
You might wanna lose the Sync part. Only readFile
when you have a callback.
Also: ./path, not /path.
精彩评论