node.js - How to use node's fs module in a browser environment?
高洛峰
高洛峰 2017-05-16 13:44:07
0
2
1233

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

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all (2)
Ty80

fileReader?

    仅有的幸福

    First of all, let’s be clear, JavaScript code similar to thebrowserify这样的工具仅仅能将使用commonjsmodule 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 infile uploader中上传的文件预处理,那么你该使用浏览器端原生的FileReaderAPI

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!