[英]How do I access and read a local file from html+javascript page running locally
[英]How to read a local file in Javascript (Running from an Electron App)
我已經搜索了一個多小時左右,但我找不到我的問題的答案。 有沒有辦法從本地文件中獲取文本,只使用一個普通的舊文件 URL?
我找到了許多通過文件輸入 HTML 標記來讀取文件的方法,但是我有一個難以置信的痛苦,在我的 PC 上找到一個可以找到文件的代碼示例,只使用普通的舊 JS。
該代碼將位於 electron 應用程序中。
我需要代碼示例。 像這樣的東西:
readFile("file:\\\\C:\path\to\file.txt","text/plain");
readFile(url,mimetype){
....
}
如果要讀取 Electron 中的文件,則必須了解 Electron 應用程序的各個部分。 簡而言之,有一個主進程和一個渲染器進程。 主進程擁有並被授予使用節點模塊的所有控制權,例如可以讀取文件的fs
模塊。 渲染器進程不應該訪問fs
模塊,而是當它需要使用fs
模塊時,它應該請求主進程使用fs
,然后返回結果。
僅供參考,渲染器進程是 web 頁面,您的 Electron 應用程序的可見部分。
這種通信稱為 IPC(進程間通信)。 流程是:
fs
讀取一個文件下面是一個非常粗略的例子。
索引.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));
}
}
}
);
免責聲明:我是流行的安全 electron 模板的作者,並編寫了有關如何使用fs
在 Electron 應用程序中讀取文件的具體指南。 我希望你能讀一讀,因為那里有更多信息。
如果我沒記錯的話,使用這樣的東西應該適用於 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.