【问题标题】:electron, after browserify, fs.existsSync is not a functionelectron,browserify之后,fs.existsSync不是函数
【发布时间】:2017-08-23 12:51:42
【问题描述】:

我阅读了很多关于 browserify 和 electron 以及 gui 浏览器问题的信息 但是browserify还是有问题,说“fs.existsSync不是函数”,“required没有定义”

* 全文* 我用电子创建了简单的 gui, 有 package.json 文件、main.js 和 index.html 文件 + 3,4 个 html 文件,我想在其中创建与 require 一起使用的简单“加载显示保存窗口”

该功能在 index.html 文件中有效,但在 load.html 文件中无法正常工作,因此我使用命令浏览 main.js

var  fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote 

进入 main.bundle3.js,使用,(在 cmd 中)

browserify main.js > main.bundle3.js 

然后 load.html 文件大喊 require 没有定义和

> main.bundle3.js:6945 Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (main.bundle3.js:6945)
    at Object.require.36.fs (main.bundle3.js:6951)
    at s (main.bundle3.js:1)
    at main.bundle3.js:1
    at Object.<anonymous> (main.bundle3.js:6794)
    at Object.require.35._process (main.bundle3.js:6937)
    at s (main.bundle3.js:1)
    at e (main.bundle3.js:1)
    at main.bundle3.js:1
(anonymous) @   main.bundle3.js:6945
require.36.fs   @   main.bundle3.js:6951
s   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:6794
require.35._process @   main.bundle3.js:6937
s   @   main.bundle3.js:1
e   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1  

package.json

{
  "name": "RDF",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "test": "mocha -u exports -R spec test/index"
  },
  "devDependencies": {
    "electron": "^1.6.2",
    "electron-packager": "^8.6.0",
    "html-browserify": "0.0.6",
    "jquery": "^3.2.1"
  }
}
和 load.html 文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<!--<script src="main.js"></script>-->
    <script src="main.bundle3.js"></script>
  <!--    <script type="text/javascript" src="main.js"></script> -->
        <script type="text/javascript" src="./lib/jquery-1.7.2.min.js"></script>
 </head>
         <body>
<h3>LOAD</h3>
<p>load the data</p>
<!--
<input type="button" value="Details" onclick="javascript:$('#mainContainer').load('index.html');"/><br>
<div id="mainContainer">  </div>-->

<div id="tab33">
  <div>
        <div style="text-align:center;">
            <input type="text" placeholder="just select a file" id="actual-file" disabled="disabled"/>
            <input type="button" value="Choose a file" id="select-file"/>
        </div>
        <br><br>
        <textarea id="content-editor" rows="5"></textarea><br><br>
        <input type="button" id="save-changes" value="Save changes"/>
        <input type="button" id="delete-file" value="Delete file"/>
    </div>
    <hr>  <div style="text-align:center;">
        <p>  he file content will be the same as the editor.  </p>
        <input type="button" value="Choose a file" id="create-new-file"/>
    </div>
      <script>
      var  fs = require('fs')
      var {remote} = require('electron').remote  ;
      var {dialog} = require('electron').remote

         document.getElementById('select-file').addEventListener('click',function(){
             dialog.showOpenDialog(function (fileNames) {
                 if(fileNames === undefined){
                     console.log("No file selected");
                 }else{
                     document.getElementById('actual-file').value = fileNames[0];
                     readFile(fileNames[0], fileReadComplete);
                 }
             });
         },false);
  //
           document.getElementById('save-changes').addEventListener('click',function(){
             var actualFilePath = document.getElementById("actual-file").value;

             if(actualFilePath){
                 saveChanges(actualFilePath,document.getElementById('content-editor').value);
             }else{
                 alert("just select a file first");
             }
         },false);
  //
         document.getElementById('delete-file').addEventListener('click',function(){
             var actualFilePath = document.getElementById("actual-file").value;

             if(actualFilePath){
                 deleteFile(actualFilePath);
                 document.getElementById("actual-file").value = "";
                 document.getElementById("content-editor").value = "";
             }else{
                 alert("just select a file first");
             }
         },false);

         document.getElementById('create-new-file').addEventListener('click',function(){
             var content = document.getElementById("content-editor").value;

             dialog.showSaveDialog(function (fileName) {
                 if (fileName === undefined){
                     console.log("You didn't save the file");
                     return;
                 }

                 fs.writeFile(fileName, content, function (err) {
                     if(err){
                         alert("An error ocurred creating the file "+ err.message)
                     }

                     alert("The file has been succesfully saved");
                 });
             });
         },false);
            function fileReadComplete(data) {
             myData = data;
             // Do whatever you want
         }
         function readFile(filepath, callback) {
       fs.readFile(filepath, 'utf-8', function (err, data) {
           if(err){
               alert("An error ocurred reading the file :" + err.message);
               return;
           }
           callback(data);
           document.getElementById("content-editor").value = data;
       });
   }

         function deleteFile(filepath){
             fs.exists(filepath, function(exists) {
                 if(exists) {
                     // File exists deletings
                     fs.unlink(filepath,function(err){
                         if(err){
                             alert("An error ocurred updating the file"+ err.message);
                             console.log(err);
                             return;
                         }
                     });
                 } else {
                     alert("This file doesn't exist, cannot delete");
                 }
             });
         }

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

                 alert("The file has been succesfully saved");
             });
         }
     </script>
  </div>

<!--   <script data-main="main" src="require.js"></script>-->
</body>
</html>

完整的 main.js 文件

//console.log(require('fs'));
console.log(require('module').globalPaths);
const {
  electron
} = require('electron');
const {
  BrowserWindow
} = require('electron')
const {
  app
} = require('electron');
//  @show(app)
const path = require('path')
//console.log( process.env.PATH);
// (D:\electron-v1.6.1-win32-x64\resources\default_app.asr\main.js:325:5)
 //const BrowserWindow = require('browser-window')
const url = require('url')
var html = require('html-browserify');
var fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote
//dialog = require('electron').dialog
//dialog =remote.require('dialog')

//var load_=require('./load_.js')
// broserify html
var through = require('through');
var htmlclean = require('htmlclean');

module.exports = function(file, options) {

  options = options || {};  
  options.htmlclean =
   typeof options.htmlclean !== 'undefined' 
      ?      options.htmlclean : true;

  var buffer = '';

  if (!/\.(tpl|html)/.test(file)) {

    return through();

  } else {

    return through(function(chunk) {

      return buffer += chunk.toString();

    }, function() {

      var jst = buffer.toString();

      if (options.htmlclean) {
        //options.htmlclean is truthy

        if (typeof options.htmlclean === 'object') {
          //options.htmlclean is an options object for the htmlclean module
          jst = htmlclean(jst, options.htmlclean);
        } else {
          //otherwise, clean using default options
          jst = htmlclean(jst);
        }
      }

      var compiled = 'module.exports = ';
      compiled += JSON.stringify(jst);
      compiled += ';\n';

      this.queue(compiled);
      return this.queue(null);

    });

  }

}
//requirejs.config({
//By default load any module IDs from js/lib
//  baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
//paths: {
//  app: '  '
//}
//});

// Start the main app logic.
//requirejs(['jquery', 'canvas', 'app/sub'],
//function   ($,        canvas,   sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
//});
//const fs = require('fs');
//const app = require('electron').app.
//const remote = require('electron').remote;

   
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1050,
    height: 814
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

【问题讨论】:

  • 没有答案 - 但browserfy 与桌面应用程序相关吗?
  • 在electron中,应用是基于浏览器的; “require(module)”的问题与人们在其他基于浏览器的应用程序、应用程序到浏览器(例如网站等)中谈论的问题相同

标签: javascript html browserify electron require


【解决方案1】:

Browserify 忽略“fs”导入并在其位置返回一个空对象(请参阅此处:https://github.com/browserify/browserify-handbook#ignoring-and-excluding)。

您必须从 browserify 包中排除 node_modules 模块,如下所示:

gulp.task('default', () => {
  var b = browserify('src/electron.js', {
    debug: true,
    ignoreMissing: true,
    builtins: false,
    commondir: false,
    detectGlobals: false
  });
  b.exclude('fs');  // HERE
  b.exclude('electron');
  b.exclude('electron-updater');
  b.exclude('electron-settings');
  b.exclude('path');
  b.exclude('url');
  b.exclude('sqlite3');
  b.exclude('express');
  b.exclude('net');
  b.exclude('body-parser');
  b.bundle()
    .pipe(source('electron.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./src'));
});

现在您的应用程序将直接从 node_modules 获取模块,而不是一个空对象。

【讨论】:

  • 我遇到了同样的问题,这对我来说是正确的答案。但是,就我而言,正确的 browserify api 是 external,而不是 exclude。 external 将不理会每个 require 调用,委托给外部框架(在本例中为电子/节点);而 exclude 将简单地从包中删除模块,仍然与 require 调用混淆。
【解决方案2】:

如果您在需要电子之前改为declare const window: any;,那么您可以添加“窗口”。根据您的要求又名const {...} = window.require('electron')...;

【讨论】:

    【解决方案3】:

    这个问题与require 方法有关。要修复它,您应该使用window.require。

    【讨论】:

    • 但是如果我没有定义 window 怎么办?
    【解决方案4】:

    这个问题的概念解决方案: 在“电子”中,
    “{dialog}=require(electron)”(例如,) 在标签中,将不起作用

    这就是他们制造电子的方式。 可能是为了提高稳定性或只是基于 chrome 的部分问题

    在主进程中,我们可以 require(electron),在 tabs 中,我们需要使用 browserify 的 npm 模块 *** 检查例如 what modules work where in electron

    【讨论】:

      【解决方案5】:

      *** 技术方案是从 index.html 文件中一个接一个地链接文件,每个文件中都有 js 文件与 require 一起工作

      *** 错误“fs.existsSync 不是函数”是一般错误。在未直接连接到主文件(index.html 和 main.js)的文件中出现 require() 问题的地方

      *** 所有其他解决方案都失败了(许多出现在 Internet 上的 browserify、webpack、webview、requirejs 等)

      【讨论】:

        【解决方案6】:

        命令好了

        npm install browserify-fs 
        

        然后是

        browserify -fs main.js >main.bundle.js
        

        解决了“fs.existsSnc 不是函数”,但不是问题。可能只是从问题中删除 fs 。 (出现这个的原因:那个回复出现在question about fs and browserify)

        【讨论】:

          猜你喜欢
          • 2019-12-27
          • 1970-01-01
          • 2016-06-11
          • 2019-08-13
          • 2018-03-11
          • 2019-05-19
          • 2020-08-12
          • 1970-01-01
          • 2020-01-23
          相关资源
          最近更新 更多