尝试从桌面读取节点js的文件时出错 [英] Error while trying to read file with node js from desktop

查看:150
本文介绍了尝试从桌面读取节点js的文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码从我的桌面读取简单文件

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);
        });

    });

当我点击浏览器/ aa我收到以下错误

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' }

如果我返回 res.send(test)我可以在浏览器中看到测试...
任何想法我在这里想念什么?

if I return instead res.send("test") i able to see in the browser test... any idea what I miss here ?

推荐答案

由于安全原因,Web服务器被限制为当前目录。所以如果你想到达一些文件,首先移动到Web服务器的目录。只是为了证明这个概念你可以尝试这个代码:

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.

这篇关于尝试从桌面读取节点js的文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆