问题
Im using the following code to read simple file from my desktop
module.exports = function (app) {
app.get('/aa', function(req, res) {
fs = require('fs');
fs.readFile('C:\\Users\\t56789\\Desktop\\myfile.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
res.send(data);
});
});
when I hit in the browser /aa i got the following error
{ [Error: ENOENT, open 'C:\Users\t56789\WebstormProjects\Ro0.1\?C:\Users\t56789\Desktop\myfile.txt']
errno: -4058,
code: 'ENOENT',
path: 'C:\Users\t56789\WebstormProjects\Ro0.1\?C:\Users\t56789\Desktop\myfile.txt' }
if I return instead res.send("test") i able to see in the browser test...
any idea what I miss here ?
回答1:
Because of the security reasons the web server is limited to it's current directory. So if you want to reach some file move it first to the web server's directory. Just to prove the concept you could try this code:
app.get('/aa', function (req, res) {
var fs = require('fs');
fs.readFile(__filename, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
console.log(data);
res.send(data);
});
});
It will display the content of the file where the code is.
来源:https://stackoverflow.com/questions/30660250/error-while-trying-to-read-file-with-node-js-from-desktop