Error while trying to read file with node js from desktop

我的梦境 提交于 2020-01-23 03:22:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!