簡體   English   中英

如何讀取 Javascript 中的本地文件(從 Electron 應用程序運行)

[英]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(進程間通信)。 流程是:

  1. Renderer 進程通過 IPC 向主進程發送消息
  2. 主進程聽到消息,然后用fs讀取一個文件
  3. 內容/結果通過 IPC 發送回渲染器進程
  4. 渲染器進程現在可以用文件中的數據做它想做的事

下面是一個非常粗略的例子。

索引.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");
  1. 讀取文件是使用節點完成的,不依賴於 electron
  2. 如果您有創建 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(/\\/,'\\\\')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM