我正在用 Javascript 开发一个应用程序,它需要读取文本文件并将其作为输入放入变量中。但是,我google了很多相关问题,发现由于安全原因,FileReader无法在没有文件输入的情况下读取文件。是否有任何库或肮脏的方法来读取仅使用本地路径的文本文件的内容?非常感谢。
我认为一种方法是使用 Ajax 加载文件。然后你就可以用它的内容做任何你想做的事。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Do whatever you want here with this.responseText
}
};
xhttp.open("GET", "youtext.txt", true);
xhttp.send();
将 file.txt 或 file.json 放入本地主机或将其放在服务器上会更容易。
或者这个链接也许可以帮助你 https://github.com/nwjs/nw.js/issues/3227
我理解这个问题,他想从本地路径中逐行读取文件。
在尝试显示 TypeScript 文件 ElasticBounce.tsx(在 Next.js 应用程序中使用)的原始文本内容时遇到了同样的问题,以便在 Monaco Editor 中呈现文件内容。
// app/api/read-file/route.ts
import { promises as fs } from "fs";
import { NextResponse } from "next/server";
import path from "path";
export async function GET() {
// ./components/features/elasticBounce/ElasticBounce.tsx
const filePath = path.join(
process.cwd(),
"components",
"features",
"elasticBounce",
"ElasticBounce.tsx"
);
try {
const fileContent = await fs.readFile(filePath, "utf8");
return new NextResponse(fileContent, {
status: 200,
headers: { "Content-Type": "text/plain" },
});
} catch (error) {
console.error("Error reading the file", error);
return new NextResponse("Error reading the file", { status: 500 });
}
}
并像这样使用读取文件端点:
"use client";
import Editor, { Monaco } from "@monaco-editor/react";
import { useEffect, useState } from "react";
import { solarizedDarkTheme } from "./pointCode";
export const EditorWaves = () => {
const [code, setCode] = useState<string>("");
const handleEditorWillMount = (monaco: Monaco) => {
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true,
});
monaco.editor.defineTheme("solarized-dark", {
base: "vs-dark",
inherit: true,
rules: solarizedDarkTheme.rules,
colors: solarizedDarkTheme.colors,
});
};
useEffect(() => {
fetch("/api/read-file")
.then((response) => response.text()) // Utiliser response.text() au lieu de response.json()
.then((data) => {
setCode(data); // Stocker directement le texte dans fileContent
})
.catch((error) => console.error("Error fetching file:", error));
}, []);
return (
<Editor
className="rounded-3xl"
width="800px"
height="600px"
language="typescript"
theme="solarized-dark"
value={code}
options={{
selectOnLineNumbers: true,
automaticLayout: true,
minimap: { enabled: false },
wordWrap: "on",
folding: true,
lineNumbersMinChars: 3,
fontSize: 14,
fontFamily: "monospace",
fontWeight: "normal",
fontLigatures: true,
roundedSelection: true,
}}
onChange={(newValue) => {
try {
const newParams = eval(newValue || "");
setCode(newParams);
} catch (e) {
console.error("Erreur dans l'évaluation du code:", e);
}
}}
beforeMount={(monaco) => handleEditorWillMount(monaco)}
/>
);
};