如何在 Javascript 中读取本地文件(从 Electron 应用程序运行)

问题描述 投票:0回答:4

我已经搜索了一个多小时左右,但找不到我的问题的答案。有没有办法只使用普通的旧文件 URL 从本地文件获取文本?

我发现了多种通过文件输入 HTML 标签读取文件的方法,但我遇到了令人难以置信的痛苦,找到一个可以在我的 PC 上查找文件的代码示例,仅使用普通的旧 JS。

代码将位于电子应用程序内。

我需要代码示例。像这样的东西:

readFile("file:\\\\C:\path\to\file.txt","text/plain");

readFile(url,mimetype){
 ....
}
javascript file methods io electron
4个回答
25
投票

如果你想在 Electron 中读取文件,你必须了解 Electron 应用程序的各个部分。在short中,有一个main进程和一个renderer进程。主进程拥有并被授予使用节点模块的所有控制权,例如可以读取文件的

fs
模块。渲染器进程不应该访问
fs
模块,而是在需要使用
fs
模块时,它应该要求主进程使用
fs
,然后返回结果。

仅供参考,渲染器进程是网页,是 Electron 应用程序的可见部分。

这种通信称为IPC(进程间通信)。流程是:

  1. 渲染进程通过IPC向主进程发送消息
  2. 主进程听到消息,然后用
    fs
  3. 读取文件
  4. 内容/结果通过IPC发送回渲染器进程
  5. 渲染器进程现在可以对文件中的数据执行所需操作

下面是一个非常粗略的示例。

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);
  });
});

预加载.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应用程序中读取文件的

特定指南
。我希望您阅读一下,因为其中包含更多信息。


0
投票
  1. 读取文件是使用node完成的,不依赖于电子
  2. 在有创建窗口的代码的地方添加此代码
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(/\\/,'\\\\')


0
投票
async readFileContent(filePath) {
    try {
        const response = await fetch(filePath);
        if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
        const text = await response.text();
        console.log('file content:', text);
    } catch (error) {
        console.error(`Error loading file: ${error.message}`);
    }
}

-3
投票

如果我没记错的话,使用这样的东西应该可以与 fs 模块一起使用。

fs.readFileSync("/path/to/file.txt");
© www.soinside.com 2019 - 2025. All rights reserved.