[英]How to read a local file in Javascript (Running from an Electron App)
I have been searching for over an hour or so, and I cant find an answer to my question.我已经搜索了一个多小时左右,但我找不到我的问题的答案。 Is there a way to get the text from a local file, using just a plain old file URL?有没有办法从本地文件中获取文本,只使用一个普通的旧文件 URL?
I have found numerous ways to read a file via file input HTML tag, but I have had an incredible pain, finding a code example that can find a file, on my PC, using just plain old JS.我找到了许多通过文件输入 HTML 标记来读取文件的方法,但是我有一个难以置信的痛苦,在我的 PC 上找到一个可以找到文件的代码示例,只使用普通的旧 JS。
The code will be inside an electron application.该代码将位于 electron 应用程序中。
I need code examples.我需要代码示例。 Something like this:像这样的东西:
readFile("file:\\\\C:\path\to\file.txt","text/plain");
readFile(url,mimetype){
....
}
If you want to read a file in Electron, you have to understand the various parts of an Electron app.如果要读取 Electron 中的文件,则必须了解 Electron 应用程序的各个部分。 In short , there is a main process and a renderer process.简而言之,有一个主进程和一个渲染器进程。 The main process has and is given all control to use node modules, such as the fs
module that can read files.主进程拥有并被授予使用节点模块的所有控制权,例如可以读取文件的fs
模块。 The renderer process should not have access to the fs
module, but instead anytime it needs to use the fs
module, it should ask the main process to use fs
, and then return the result.渲染器进程不应该访问fs
模块,而是当它需要使用fs
模块时,它应该请求主进程使用fs
,然后返回结果。
FYI the renderer process is the web page, the visible part of your Electron app.仅供参考,渲染器进程是 web 页面,您的 Electron 应用程序的可见部分。
This communication is called IPC (inter-process communication).这种通信称为 IPC(进程间通信)。 The flow is:流程是:
fs
主进程听到消息,然后用fs
读取一个文件A very rough example is below.下面是一个非常粗略的例子。
index.html索引.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
// Called when message received from main process
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
// Send a message to the main process
window.api.send("toMain", "some data");
</script>
</body>
</html>
main.js main.js
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents
// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});
preload.js preload.js
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
DISCLAIMER: I'm the author of a popular secure electron template , and have wrote a specific guide on how to use fs
to read a file in an Electron app.免责声明:我是流行的安全 electron 模板的作者,并编写了有关如何使用fs
在 Electron 应用程序中读取文件的具体指南。 I hope you give it a read because it has additional information there.我希望你能读一读,因为那里有更多信息。
if im not mistaken, using something like this should work with the fs module.如果我没记错的话,使用这样的东西应该适用于 fs 模块。
fs.readFileSync("/path/to/file.txt");
const fs = require("fs");
function readFile(fileURL,mimeType){
//readfile does not accept the file:\\\ thing, so we remove it
const pathToFile = fileURL.replace("file:\\\\",'');
fs.readFile(pathToFile,mimeType,(err,contents)=>{
if(err){
console.log(err);
return;
}
console.log(contents);
})
}
readFile('C:\\Users\\<userAccount>\\Documents\\test.txt','utf8')
//If your on windows you'll need to use double backslashes for the paths
//here's an example regex to do that
pathToFile = pathToFile.replace(/\\/,'\\\\')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.