简体   繁体   English

尝试从桌面使用Node JS读取文件时出错

[英]Error while trying to read file with node js from desktop

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 当我在浏览器中/ aa命中时,出现以下错误

{ [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 ? 如果我改为返回res.send("test")我就能在浏览器中看到测试...任何想法我在这里错过了吗?

Because of the security reasons the web server is limited to it's current directory. 由于安全原因,Web服务器仅限于其当前目录。 So if you want to reach some file move it first to the web server's directory. 因此,如果要访问某些文件,请先将其移至Web服务器的目录。 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. 它将显示代码所在文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM