Use fs module in React.js,node.js, webpack, babel,express

六月ゝ 毕业季﹏ 提交于 2019-11-29 10:16:56

Errors

First let's go through your errors a little bit:

When you don't use npm run build or npm run start, you won't use webpack and therefore the require statement doesn't get replaced with the contents of the fs module--instead you are left with a require statement, which your browser doesn't understand since require is a Node-only function. Thus, your error about require not being defined.

If you do run with npm run build or npm run start, webpack takes that require statement out and replaces it with the fs module. But, as you've discovered, fs doesn't work on the client side.

Alternatives

So, if you can't use fs to save files, what can you do?

If you are trying to save the file to a server, you have to submit data from your form to the Node server, and the Node server can use fs to interact with the server's filesystem to save the file.

If you are trying to save the form locally, i.e., on the same device as the browser, you need to use another strategy like this or by using a client-side library like FileSaver. Which option you take depends somewhat on your use case, but if you are trying to save on the client side you can search around "saving files from web browser" or "saving files client side" to see what works for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!