【问题标题】:Reading local file from absolute path in node fs module从节点 fs 模块中的绝对路径读取本地文件
【发布时间】:2016-12-06 11:47:05
【问题描述】:

我正在尝试使用 node js 'fs' 模块从本地系统读取文件。但是由于某种原因,当我通过绝对路径时,“fs”模块不起作用。

代码:

let filePath = "/home/mysystem/dev/myproject/sayHello.txt";
let newFile=fs.readFileSync('file://'+filePath);

代码抛出错误为:

Uncaught Error: ENOENT: no such file or directory, open 'file:///home/mysystem/dev/myproject/sayHello.txt'

但我可以使用相同的路径从浏览器窗口打开文件。 如果我通过相对路径,fs 模块正在工作。我在使用电子框架构建的应用程序中使用它。

【问题讨论】:

  • NodeJS 不需要 file 协议。只需尝试阅读 filePath 而不使用 "file://"
  • 谢谢你! .我试图解决这个问题很长时间。 :)
  • @zfor 你能把你的评论变成答案吗?

标签: javascript node.js npm electron fs


【解决方案1】:

我对此感到困惑。如果在 Windows 上使用 Angular 2 和 Typescript,您的绝对路径将如下所示:

import { readdirSync } from "fs";
. . .
let x = readdirSync("C:/SAFE/Dir1/Blah");
console.log("files retrieved="+ x.length);

【讨论】:

    【解决方案2】:

    在 NodeJS 中,您不必使用file 协议来读取文件。

    你可以去掉"file://"部分,尝试直接阅读filePath

    let filePath = "/home/mysystem/dev/myproject/sayHello.txt";
    let newFile = fs.readFileSync(filePath);
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2019-06-22
      • 1970-01-01
      • 2020-12-30
      • 2014-07-15
      相关资源
      最近更新 更多