我目前在我的应用程序中使用 React 和 Node js。
我正在尝试从文本文件中读取数据,当我尝试不同的操作时,会出现不同的错误。通过研究,从文件读取的最简单路径是使用“fs”,因此我将发布我尝试从本地文件(客户端)读取的两种方法。
如果有人可以帮助解决我的错误,或者甚至向我展示从本地文件读取的不同方式,我将不胜感激!
import React ...
import { readFile, readFileSync } from 'fs';
// other imports
class Background extends Component {
// my constructor
componentDidMount() {
this.loadMe();
}
loadMe() {
var file = './read_file';
/* WAY 1: Asynchronously using readFile */
readFile(file, function(err, data) {
if (err) { console.log(err) }
console.log(data);
}
/* WAY 2: Synchronously using readFileSync */
var data = readFileSync(file);
console.log(data);
}
}
显然,我不会同时双向跑步。我基本上还从其他堆栈溢出答案和一些在线教程中复制了代码。我研究了
FileReader
但无法使其发挥作用。
我当前收到的错误:
TypeError: Object(...) is not a function
指向var data = readFileSync(file);
谢谢!
fs
是一个为服务器 JS env(如 NodeJS)保留的库。
无法直接从浏览器打开和编辑文件。 然而,它可以打开文件,编辑然后下载编辑后的文件。
您需要一个具有
input
类型的 file
元素,因为这样浏览器可以保证页面仅访问用户明确选择的文件。 (如果评论中不清楚,请告诉我。如果不清楚,我会尽力解释得更好。)
在下面的示例中,我将使用
textarea
元素来编辑文件的内容,但是一旦您将内容存储在字符串变量中,您就可以在代码中或以您喜欢的方式更改它。
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<meta charset="utf-8"/>
<script>
document.addEventListener('DOMContentLoaded',function() {
var fileInput = document.getElementById("fileInput");
var textArea = document.getElementById("fileEditor");
var saveFileButton = document.getElementById("saveFileButton");
var downloadAnchor = document.getElementById("downloadAnchor");
function base64EncodeUnicode(str) {
// First we escape the string using encodeURIComponent to get the UTF-8 encoding of the characters,
// then we convert the percent encodings into raw bytes, and finally feed it to btoa() function.
utf8Bytes = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
});
return btoa(utf8Bytes);
}
function handleInputFileChange(event) {
//if we didnd't already have the "fileInput" var in scope, we could use "event.target" to get it
if(fileInput.files.length>=1) {
//In this example, I'm putting the selected file's name in the title. You don't need to do this
document.title = fileInput.files[0].name;
downloadAnchor.setAttribute("download","edited_"+fileInput.files[0].name);
}
else {
document.title = "FileReader Example";
downloadAnchor.setAttribute("download","edited_file.txt");
}
var fr = new FileReader();
fr.readAsText(fileInput.files[0]);
fr.onload = function (event) {
//Both "event.target.result" and "fr.result" contain the file's contents (because "event.target" is === "fr")
textArea.value = event.target.result;
// OR
//textArea.value = fr.result;
}
}
//The next is the fucntion returns a special kind of URL, a Data URL.
//These kind of URLs don't point to a file, they ARE the data.
//Read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
function getDownloadableTextAreaContents() {
return "data:text/plain,"+encodeURIComponent(textArea.value);
}
function onDownloadClick(event) {
//https://stackoverflow.com/a/247261/6302540
//var urlObject = "data:text/plain;base64,"+btoa(unescape(encodeURIComponent(textArea.value)));
var urlObject = getDownloadableTextAreaContents();
downloadAnchor.setAttribute("href",urlObject);
downloadAnchor.click();
}
fileInput.addEventListener("change",handleInputFileChange);
saveFileButton.addEventListener("click",onDownloadClick);
},false);
</script>
</head>
<body>
<h1>File Reader Example:</h1>
<input id="fileInput" type="file" accept=".txt"/>
<textarea name="File Editor" id="fileEditor" placeholder="Your file's contents will show up here once you select the file!"></textarea>
<button id="saveFileButton">Save File</button>
<!--The next <a> tag is just a trick to make the browser download a file. It isn't displayed (style="display: none;")-->
<a id="downloadAnchor" download="edited_file.txt" href="data:text/plain," style="display: none;"></a>
</body>
</html>
这是纯 JS 中的示例,但您可以轻松地对其进行调整以做出反应。一些调整是:
受控的
textarea
组件,而不是简单的textarea
。使用受控组件可以轻松设置和获取文本区域的值。 (如果你不理解 React 的 state 和 props 或受控组件如何工作,你可以使用引用(这使得 React 代码几乎相同并且是纯 JS),但我严重不推荐它,因为它是一种反模式,并且只应在极少数情况下使用,例如一些非常非常、、、、very奇特的动画);
change
和
click
属性可以轻松转换
onChange
和
onClick
事件;
downloadAnchor.click()
,你可以按照这个答案
<a>
) 的
href
和
download
属性也可以是具有状态值的普通 prop,例如:
<a download={this.state.downloadFilename} href={this.state.dataURL} style="display: none;"/>
https://github.com/kentcdodds/babel-plugin-preval 的内容在前端 React 应用程序中使用 fs 模块。
安装 preval.macro
npm i preval.macro --save
import preval from 'preval.macro';
const components = preval
` const fs = require('fs');
const files = fs.readdirSync('src/atoms');
module.exports = files;
`
组件将返回 src/atoms 下的文件夹。
import file from '../documents/doc.pdf';
const bytes = await fetch(file).then(res => res.arrayBuffer())