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

时间:2021-02-18 18:43:27

标签: javascript file methods io electron

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

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

代码将在电子应用程序中。

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

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

readFile(url,mimetype){
 ....
}

3 个答案:

答案 0 :(得分:1)

如果您想在 Electron 中读取文件,您必须了解 Electron 应用程序的各个部分。 简而言之,有一个进程和一个渲染器进程。主进程拥有并被授予所有使用节点模块的控制权,例如可以读取文件的 fs 模块。渲染进程不应该访问fs模块,而是在需要使用fs模块时,它应该要求主进程使用fs,然后返回结果.

<块引用>

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

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

  1. Renderer 进程通过 IPC 向主进程发送消息
  2. 主进程听到消息,然后读取带有fs的文件
  3. 内容/结果通过 IPC 发送回渲染器进程
  4. 渲染器进程现在可以使用文件中的数据做它想做的事情

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

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>

ma​​in.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));
            }
        }
    }
);

免责声明:我是一个流行的 secure electron template 的作者,并且写了一个关于如何使用 fs 在 Electron 应用程序中读取文件的 specific guide。我希望你能读一读,因为它有额外的信息。

答案 1 :(得分:0)

如果我没记错的话,使用这样的东西应该适用于 fs 模块。

fs.readFileSync("/path/to/file.txt");

答案 2 :(得分:0)

  1. 读取文件是使用节点完成的,不依赖于电子
  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(/\\/,'\\\\')