简体   繁体   English

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

[英]How to read a local file in Javascript (Running from an Electron App)

I have been searching for over an hour or so, and I cant find an answer to my question.我已经搜索了一个多小时左右,但我找不到我的问题的答案。 Is there a way to get the text from a local file, using just a plain old file URL?有没有办法从本地文件中获取文本,只使用一个普通的旧文件 URL?

I have found numerous ways to read a file via file input HTML tag, but I have had an incredible pain, finding a code example that can find a file, on my PC, using just plain old JS.我找到了许多通过文件输入 HTML 标记来读取文件的方法,但是我有一个难以置信的痛苦,在我的 PC 上找到一个可以找到文件的代码示例,只使用普通的旧 JS。

The code will be inside an electron application.该代码将位于 electron 应用程序中。

I need code examples.我需要代码示例。 Something like this:像这样的东西:

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

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

If you want to read a file in Electron, you have to understand the various parts of an Electron app.如果要读取 Electron 中的文件,则必须了解 Electron 应用程序的各个部分。 In short , there is a main process and a renderer process.简而言之,有一个进程和一个渲染器进程。 The main process has and is given all control to use node modules, such as the fs module that can read files.主进程拥有并被授予使用节点模块的所有控制权,例如可以读取文件的fs模块。 The renderer process should not have access to the fs module, but instead anytime it needs to use the fs module, it should ask the main process to use fs , and then return the result.渲染器进程不应该访问fs模块,而是当它需要使用fs模块时,它应该请求主进程使用fs ,然后返回结果。

FYI the renderer process is the web page, the visible part of your Electron app.仅供参考,渲染器进程是 web 页面,您的 Electron 应用程序的可见部分。

This communication is called IPC (inter-process communication).这种通信称为 IPC(进程间通信)。 The flow is:流程是:

  1. Renderer process sends a message to the main process over IPC Renderer 进程通过 IPC 向主进程发送消息
  2. The main process hears the message, and then reads a file with fs主进程听到消息,然后用fs读取一个文件
  3. The contents/result are sent back via IPC to the renderer process内容/结果通过 IPC 发送回渲染器进程
  4. The renderer process now can do what it wants with the data from the file渲染器进程现在可以用文件中的数据做它想做的事

A very rough example is below.下面是一个非常粗略的例子。

index.html索引.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 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 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));
            }
        }
    }
);

DISCLAIMER: I'm the author of a popular secure electron template , and have wrote a specific guide on how to use fs to read a file in an Electron app.免责声明:我是流行的安全 electron 模板的作者,并编写了有关如何使用fs在 Electron 应用程序中读取文件的具体指南 I hope you give it a read because it has additional information there.我希望你能读一读,因为那里有更多信息。

if im not mistaken, using something like this should work with the fs module.如果我没记错的话,使用这样的东西应该适用于 fs 模块。

fs.readFileSync("/path/to/file.txt");
  1. Reading a file is done using node and is not dependent on electron读取文件是使用节点完成的,不依赖于 electron
  2. Where you have the code for creating a window add this code如果您有创建 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.

相关问题 如何从本地运行的 html+javascript 页面访问和读取本地文件 - How do I access and read a local file from html+javascript page running locally Javascript,如何读取本地文件? - Javascript, how to read local file? 如何在javascript中从D盘读取本地文件 - How can i read local file from D drive in javascript 如何使用JavaScript从本地文件读取CSS规则 - How can i read CSS rule from local file with JavaScript 如何从javascript中的本地.csv文件读取以填充字符串数组? - How to read from local .csv file in javascript to fill an array of strings? 电子功能读取本地文件 - FS - 不读取 - Electron function to read a local file - FS - Not reading 如何在已经运行的 Electron 应用程序中通过“打开方式”打开文件? - How to open a file through “open with” in an already running Electron app? 在 Vue CLI 3 中运行 build:electron 后,如何将静态 config.json 文件中的值读取到 Vue 文件中的 TypeScript? - How can I read values from a static config.json file to TypeScript in a Vue file after running build:electron in Vue CLI 3? 如何从 Duktape 中运行的 JavaScript 代码读取文件? - How can I read a file from JavaScript code running in Duktape? 从Java本地目录中读取文件 - Read file from local directory in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM