node.js - 在 Angular 2 + Electron 中使用绝对路径

标签 node.js angular electron fs

我开始摆弄 Angular 2 和 Electron,并使用 this starter package 。一切似乎都很顺利,我什至可以使用 Node fs 包从目录中读取。

我遇到的问题是我似乎无法使用 readdirSync() 方法的绝对路径。它只需要相对路径。

我确实在 docs for fs 中找到了这个您可以使用 URL 包来显示 readdirSync() 的绝对路径,如下所示:

const fs = require('fs');
const { URL } = require('url');

// file:///C:/tmp/hello => C:\tmp\hello
fs.readFileSync(new URL('file:///C:/tmp/hello'));

这看起来很棒,但在我的 Angular 2/TypeScript/Electron 世界中,这似乎不起作用。我的看起来像这样:

import { Injectable } from "@angular/core";
import {readdirSync} from "fs";
import { URL } from "url";


@Injectable()
export class LinkDocRetrieverService {
    getFiles():Array<String> {

        // read through all the directories to get all the files and folder names

        let u = new URL("file:///C:/SAFE/MISC");
        let x = readdirSync(u);
        console.log("files retrieved="+ x.length);

        let files: Array<string> = [];
        x.forEach(f => {
            files.push(f);
        });
        return files;
    }
}

智能感知和运行时都告诉我这一点

[ts] Argument of type 'URL' is not assignable to parameter of type 'string | Buffer'. Type 'URL' is not assignable to type 'Buffer'. Property 'write' is missing in type 'URL'.

我本以为语法是相同的,但没有运气。

我读过很多帖子,指出他们无法在 Angular 2 + Typescript 中运行 fs 包,但它对我来说效果很好,只要我使用相对路径。我只需要帮助获得工作的绝对路径。提前致谢。

最佳答案

Documentation声明 URL 支持是在 v7.6.0 中引入的,并且是实验性的。 Electron 使用 v7.4.0,因此还不能将 URL 与 fs 一起使用。

fs.readFileSync('C:/tmp/hello')

应该可以正常工作。

关于node.js - 在 Angular 2 + Electron 中使用绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44876767/

相关文章:

javascript - 更新 MongoDB 文档列表

angular - 如何将数据传递给 Angular ng-bootstrap 模态以进行绑定(bind)

angular - 在 Angular 4 中向 DOM 元素添加事件监听器

node.js - Angular、Electron、TypeScript 和 RobotJS

javascript - 将 PNG 从 GET 请求转换为 Node.js 中的可读流

javascript - 如何更改 NodeJS、Express、Passport 中输入字段的名称属性?

node.js - 谷歌 OAuth2 : Required parameter is missing: grant_type

angular - 为什么 vs19 中的断点在 angular 8 更新后停止工作?

javascript - 在 Electron/Atom Shell 中找不到模块

javascript - 在 Electron 应用程序中使用 libxml-xsd 失败并出现绑定(bind)错误