search

Home  >  Q&A  >  body text

node.js - How to use node's fs module in a browser environment?

I have a requirement, I need to use pure js to read pictures, the parameter is only the picture path, the following is the code in the node environment

var fs = require("fs");
var imageFile = fs.readFileSync('test.png', 'base64');
console.log(imageFile);

Use browserify to convert to

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

},{}],2:[function(require,module,exports){
var fs = require("fs");
var imageFile = fs.readFileSync('test.png', 'base64');
console.log(imageFile);
},{"fs":1}]},{},[2]);

When running in the browser environment, the following error appears. It seems that browserify cannot convert the fs module to run in the browser. Reading files in the browser is a difficult problem (if you do not use any html form) )
bundle.js:5 Uncaught TypeError: fs.readFileSync is not a function

高洛峰高洛峰2741 days ago1284

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 13:46:07

    fileReader?

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:46:07

    First of all, let’s be clear, JavaScript code similar to the browserify 这样的工具仅仅能将使用 commonjs module loading mechanism is converted into a form that the browser can understand. This does not mean that any Node.js code can be used on the browser side.

    The most typical example is the fs module, which is completely impossible to be called by the browser. The ability to read and write local files completely violates the security mechanism of the browser itself. Just imagine that you open a web page, and then this web page can read and write files on your local hard disk. How terrible this is!

    Therefore, your thinking itself may need to be reorganized. What functional requirements motivate you to read and write files on the web page? If it is only on the client side to the user in file uploader 中上传的文件预处理,那么你该使用浏览器端原生的 FileReader API

    reply
    0
  • Cancelreply