Javascript 电子函数读取本地文件 - FS - 不读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43722450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:07:31  来源:igfitidea点击:

Electron function to read a local file - FS - Not reading

javascriptnode.jselectron

提问by Ninjaneer

I have an electron project when I need to get electron to read a local file.

当我需要让电子读取本地文件时,我有一个电子项目。

Right now what I have is this, where it loads and displays the contents of a html file.

现在我拥有的是这个,它加载并显示一个 html 文件的内容。

I just need it to read a file and store it on a variable for now.

我现在只需要它来读取文件并将其存储在变量中。

Here is my current main.js:

这是我当前的 main.js:

 const {app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
var fs = require('fs');

let mainWindow;

function createNewWindow() {
  mainWindow = new BrowserWindow({
    width: 1300,
    height: 1000,
    minWidth: 600,
    minHeight: 400,
    title: 'Test App'
  })
}

function loadInitialUrl() {
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
}

function closeApplication() {
  mainWindow.on('closed', () => {
    mainWindow = null;
})
}


app.on('ready', function(){
  createNewWindow();
  loadInitialUrl();
  mainWindow.setMenu(null);
  mainWindow.openDevTools();
  fs.readFile('./README.md', 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }
    console.log(data);
  });
  mainWindow.on('closed', function() {mainWindow = null;});
});

How can I do this as it's not showing the contents of the README.md file in the console.log

我该怎么做,因为它没有在 console.log 中显示 README.md 文件的内容

回答by Ninjaneer

Basically you need to do the following things.

基本上你需要做以下几件事。

1.Loading required dependencies

1.加载需要的依赖

var remote = require('remote'); // Load remote compnent that contains the dialog dependency
var dialog = remote.require('dialog'); // Load the dialogs component of the OS
var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)

2.Read file content

2.读取文件内容

dialog.showOpenDialog((fileNames) => {
    // fileNames is an array that contains all the selected
    if(fileNames === undefined){
        console.log("No file selected");
        return;
    }

    fs.readFile(filepath, 'utf-8', (err, data) => {
        if(err){
            alert("An error ocurred reading the file :" + err.message);
            return;
        }

        // Change how to handle the file content
        console.log("The file content is : " + data);
    });
});

3.Update existing file content

3.更新现有文件内容

 var filepath = "C:/Previous-filepath/existinfile.txt";// you need to save the filepath when you open the file to update without use the filechooser dialog againg
var content = "This is the new content of the file";

fs.writeFile(filepath, content, (err) => {
    if (err) {
        alert("An error ocurred updating the file" + err.message);
        console.log(err);
        return;
    }

    alert("The file has been succesfully saved");
});

For more read please visit here:) Thanks..

更多阅读请访问这里:)谢谢..

One more thing to add..Please check that your path to file is correct. You could do something similar to below.

还有一件事要添加..请检查您的文件路径是否正确。你可以做类似下面的事情。

var path = require('path');
var p = path.join(__dirname, '.', 'README.md');

回答by zhuzilin

Just one update information for the accepted answer. After the update of electron, you can directly use

接受的答案只有一个更新信息。更新electron后可以直接使用

const { dialog } = require('electron');

to import dialog.

导入对话框。

And for remote, if you need to use it, you also need:

而对于远程,如果需要使用,还需要:

const { remote } = require('electron');