无法通过fs Electron + Browserify访问本地文件

时间:2019-02-22 09:09:19

标签: javascript node.js electron browserify fs

我正在为我的游戏开发一个保存功能,该功能可在Browserify上运行,Electron显示游戏。我需要能够保存游戏,当我通过终端使用它时,我想我已经弄清楚了。但是当我在Electron中运行它时,出现了这个错误:

TypeError: Cannot read property 'toString' of undefined at http://localhost:9966/Code/Scenes/tutorial.js:410:25 at http://localhost:9966/Code/Scenes/tutorial.js:33660:20 at loop (http://localhost:9966/Code/Scenes/tutorial.js:34113:20) at http://localhost:9966/Code/Scenes/tutorial.js:34101:21 at http://localhost:9966/Code/Scenes/tutorial.js:34061:36 at dispatchError (http://localhost:9966/Code/Scenes/tutorial.js:36093:7) at http://localhost:9966/Code/Scenes/tutorial.js:35591:14 at http://localhost:9966/Code/Scenes/tutorial.js:34485:14 at IDBTransaction.getTransaction.oncomplete (http://localhost:9966/Code/Scenes/tutorial.js:31262:17)
message
:
"Cannot read property 'toString' of undefined"
stack
:
"TypeError: Cannot read property 'toString' of undefined↵    at http://localhost:9966/Code/Scenes/tutorial.js:410:25↵    at http://localhost:9966/Code/Scenes/tutorial.js:33660:20↵    at loop (http://localhost:9966/Code/Scenes/tutorial.js:34113:20)↵    at http://localhost:9966/Code/Scenes/tutorial.js:34101:21↵    at http://localhost:9966/Code/Scenes/tutorial.js:34061:36↵    at dispatchError (http://localhost:9966/Code/Scenes/tutorial.js:36093:7)↵    at http://localhost:9966/Code/Scenes/tutorial.js:35591:14↵    at http://localhost:9966/Code/Scenes/tutorial.js:34485:14↵    at IDBTransaction.getTransaction.oncomplete (http://localhost:9966/Code/Scenes/tutorial.js:31262:17)"

代码:

fs.readFile('Code/JSON files/Player.save', function(err, data) {
    var saveData = data.toString()
    saveArray = saveData.split(',')
    console.log(saveArray[0])
    console.log(saveArray[1])
    console.log(saveArray[2])

  });

编辑:显然,Broswerify为fs提供了一个包装器,但是现在fs.existsSync不起作用。

  var load = require('../Functions/Load')
 // var save = require('../Functions/Save')
  var saveArray = []
  var saveData = load("Code/JSON files/Player.save")
console.log(saveData + "\n")
saveArray = saveData.split(',')
    console.log(saveArray[0])
    console.log(saveArray[1])
    console.log(saveArray[2])

加载功能:

module.exports = load
const fs = require('browserify-fs')

function load(path) {
    try {
        if (fs.existsSync(path)) {
          //file exists, read it!
          var contents = fs.readFileSync(path.toString(), 'utf8');
          return contents;
        }
      } catch(err) {
        console.error(err)
      }
}

0 个答案:

没有答案