电子,在browserify之后,fs.existsSync不是一个函数

2023-12-23

我读了很多关于 browserify 和 electro 以及 gui 浏览器问题 但 browserify 仍然存在问题,说“fs.existsSync 不是一个函数”,并且“required 未定义”

*完整的故事*我用电子创建了简单的图形用户界面, 有 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"
  }
}
and load.html file
<!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.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

电子,在browserify之后,fs.existsSync不是一个函数 的相关文章

  • 在随机位置启动 HTML5

    我有一个大约 2 小时长的音轨 我想在我的网站上使用它 我希望它在页面加载时在随机位置开始播放曲目 使用 HTML5 可以吗 我知道您可以使用 element currentTime 函数来获取当前位置 但是如何在完全下载之前获取曲目的总时
  • 如何使 d3 饼图响应式?

    我有一个 PIE 图表 它工作正常 但我无法使其具有响应能力和可调整大小 我需要它与移动浏览器和 iPad 等兼容 div div
  • 将html数据解析成python列表进行操作

    我正在尝试读取 html 网站并提取其数据 例如 我想查看公司过去 5 年的 EPS 每股收益 基本上 我可以读入它 并且可以使用 BeautifulSoup 或 html2text 创建一个巨大的文本块 然后我想搜索该文件 我一直在使用
  • 访问 nuxt 配置文件中的存储

    我想添加通过 Nuxt 静态生成的动态路由 我定义了一个客户端 服务器端存储asyncData方法 我想将这个存储值 一个数组 映射到我的nuxt config js文件使其成为 动态 静态 路线图nuxt generate命令 但如何访问
  • karma/jasmine 控制台更详细的测试结果

    我使用 Karma 和 Jasmine 进行 javascript 单元测试 假设我有一个失败的测试 如下所示 expect objectA toEqual expectedObjectA 当失败时 我看到控制台上转储了两个对象 并显示一条
  • 如何在 React Native 上显示 SVG 文件?

    我想显示 svg 文件 我有一堆 svg 图像 但我找不到显示的方式 我尝试使用Image and Use的组成部分反应本机 svg https github com magicismight react native svg但他们不这样做
  • C# 和 Javascript SHA256 哈希的代码示例

    我有一个在服务器端运行的 C 算法 它对 Base64 编码的字符串进行哈希处理 byte salt Convert FromBase64String serverSalt Step 1 SHA256Managed sha256 new S
  • 检索 css3 缩放元素的宽度/高度

    我正在与 offsetWidth 属性的奇怪之处 我认为 作斗争 这是场景 比方说 我有一个span标签 在我的js中 在某个时刻我执行css3转换 对于这个元素 例如 el set styles transform scale scale
  • JavaScript中如何确保输入的值是数字而不是字符串?

    我创建了这个函数 function num var x prompt please enter your first number var y prompt please enter your second number if isNaN
  • 如何仅显示/隐藏此 bootstrapvue 表的第二列和第三列?

    下面的代码将显示 隐藏 a 中的所有列BootstrapVue桌子 代码的来源就是这里的答案 使用 bootstrap vue 组件和 bootstrap 3 动态显示 隐藏列 https stackoverflow com questio
  • 如何将 arraylist 从 servlet 传递到 javascript?

    我通过在属性中设置数组列表并将其转发到 jsp 来从 servlet 传递数组列表 Servlet ArrayList
  • 当我多次调用 requestAnimationFrame 时会发生什么

    我的意思是一次调用多个具有相同功能的 requestAnimationFrame function Draw DoSomething function AFunc prepare something requestAnimationFram
  • 如何使用新的analytics.js跟踪多个帐户?

    我需要使用 Google 的新的analytics js 跟踪一个页面上两个帐户的综合浏览量 有大量教程和示例如何使用较旧的 ga js 进行操作 但我发现的只是这个分析文档页面 https developers google com an
  • Web组件中嵌套槽的内容不可见

    我有一个 Web 组件 它应该接受任意元素来包装其内容 虽然我可以在 Chrome 开发工具中看到插槽已正确分配 但 DOM 中什么也没有出现 以前有人见过这个问题吗 定义 class ExampleParent extends HTMLE
  • 类中可以有生成器 getter 吗?

    我的意思是吸气剂是发电机 我相信这一切都是 ES6 也许像这样 class a get count let i 10 while i yield i let b new a for const i of b count console lo
  • 语法错误:意外的标记“?”在 repl.it 上用 JavaScript 制作不和谐机器人时 [重复]

    这个问题在这里已经有答案了 我收到错误 const token this client token this client accessToken SyntaxError Unexpected token Discord 机器人代码 con
  • 如何在画布上所有其他内容后面绘制图像? [复制]

    这个问题在这里已经有答案了 我有一块画布 我想用drawImage在画布上当前内容后面绘制图像 由于画布上已经有内容 我正在使用字面上的画布来创建包含图像的画布 因此我无法真正先绘制图像 所以我无法使用drawImage在我呈现其余内容之前
  • Facebook 点赞按钮消失

    我的网站中的 Facebook Like 按钮出现问题 添加此代码 由 facebook 提供 按钮在创建时正确显示在任何页面中
  • 确定 Javascript 中的日期相等性

    我需要找出用户在 Javascript 中选择的两个日期是否相同 日期以字符串 xx xx xxxx 形式传递给该函数 这就是我需要的全部粒度 这是我的代码 var valid true var d1 new Date datein val
  • 如何映射轮播的子项数组?

    我正在尝试将 Carousel 组件包装在映射对象数组周围作为组件的子级 目前我只能让映射创建映射对象的 1 个子对象 轮播需要像这样

随机推荐