如何读取 Javascript 中的本地文件(运行 来自电子应用程序)
How to read a local file in Javascript (Running from an Electron App)
我已经搜索了一个多小时左右,但找不到问题的答案。有没有办法只使用一个普通的旧文件从本地文件中获取文本 URL?
我找到了多种通过文件输入 HTML 标签读取文件的方法,但我遇到了难以置信的痛苦,找到了一个可以在我的 PC 上找到文件的代码示例,仅使用普通的旧代码JS.
代码将在电子应用程序中。
我需要代码示例。像这样:
readFile("file:\\C:\path\to\file.txt","text/plain");
readFile(url,mimetype){
....
}
如果我没记错的话,使用类似这样的东西应该适用于 fs 模块。
fs.readFileSync("/path/to/file.txt");
如果你想在 Electron 中读取文件,你必须了解 Electron 应用程序的各个部分。在short中,有一个main进程和一个renderer进程。主进程拥有并被授予使用节点模块的所有控制权,例如可以读取文件的 fs
模块。渲染进程不应该访问 fs
模块,而是任何时候它需要使用 fs
模块,它应该要求主进程使用 fs
,然后 return结果。
FYI the renderer process is the web page, the visible part of your Electron app.
这种通信称为IPC(进程间通信)。流程是:
- 渲染进程通过IPC向主进程发送消息
- 主进程听到消息,然后用
fs
读取一个文件
- contents/result 通过 IPC 发送回渲染器进程
- 渲染器进程现在可以用文件中的数据做它想做的事
下面是一个非常粗略的例子。
index.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
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
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));
}
}
}
);
免责声明:我是关于如何使用 fs
在 Electron 应用程序中读取文件的流行 secure electron template, and have wrote a specific guide 的作者。我希望你能读一读,因为那里有更多信息。
- 读取文件是使用节点完成的,不依赖于电子
- 在您有创建代码的地方 window 添加此代码
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(/\/,'\\')
我已经搜索了一个多小时左右,但找不到问题的答案。有没有办法只使用一个普通的旧文件从本地文件中获取文本 URL?
我找到了多种通过文件输入 HTML 标签读取文件的方法,但我遇到了难以置信的痛苦,找到了一个可以在我的 PC 上找到文件的代码示例,仅使用普通的旧代码JS.
代码将在电子应用程序中。
我需要代码示例。像这样:
readFile("file:\\C:\path\to\file.txt","text/plain");
readFile(url,mimetype){
....
}
如果我没记错的话,使用类似这样的东西应该适用于 fs 模块。
fs.readFileSync("/path/to/file.txt");
如果你想在 Electron 中读取文件,你必须了解 Electron 应用程序的各个部分。在short中,有一个main进程和一个renderer进程。主进程拥有并被授予使用节点模块的所有控制权,例如可以读取文件的 fs
模块。渲染进程不应该访问 fs
模块,而是任何时候它需要使用 fs
模块,它应该要求主进程使用 fs
,然后 return结果。
FYI the renderer process is the web page, the visible part of your Electron app.
这种通信称为IPC(进程间通信)。流程是:
- 渲染进程通过IPC向主进程发送消息
- 主进程听到消息,然后用
fs
读取一个文件
- contents/result 通过 IPC 发送回渲染器进程
- 渲染器进程现在可以用文件中的数据做它想做的事
下面是一个非常粗略的例子。
index.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
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
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));
}
}
}
);
免责声明:我是关于如何使用 fs
在 Electron 应用程序中读取文件的流行 secure electron template, and have wrote a specific guide 的作者。我希望你能读一读,因为那里有更多信息。
- 读取文件是使用节点完成的,不依赖于电子
- 在您有创建代码的地方 window 添加此代码
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(/\/,'\\')