我开始摆弄 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/