“fs is not defined” How can I use fs within a VueJS file

感情迁移 提交于 2021-01-28 17:48:03

问题


I have been researching online and many others have ran in to similar problems that were left unresolved.

Why is that I can't use fs in VueJS file, I have read that it cannot be called on the client side however it is used within the docs so what am I doing wrong?

https://socket.io/docs/client-api/#With-a-self-signed-certificate

socket.js file:


const fs = require('fs');

var https = require('https').createServer(app, {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  passphrase: ''
});

chat.js file:

import io from 'socket.io-client';

const socket = io('my_public_ip:port', {
  ca: fs.readFileSync('server-cert.pem'),  //unable to read fs here
});

回答1:


It seems to me that this is rather a misconception regarding the concept of "client":

  • "Client", in socket terms, can be any software able to connect to the socket server (eg.: servers, browsers, mobile apps, games...)

  • "Server", in socket terms, is the agent responsible for accepting connections, gathering the clients.

As per the module (fs) itself, it does not work on the browser environment because it depends on the Node.js core, which comes bundled on the Node.js installation packages and is only available on Node.js servers.

On the browser side, in order to connect to secure (https) socket servers, all you need to do is set the secure parameter while connecting, as in:

const socket = io.connect('my_public_ip:port', { secure: true });



回答2:


fs is a module in the Node.js and it is not supported in a browser to forbid a direct file system operations due to security reasons.



来源:https://stackoverflow.com/questions/60729743/fs-is-not-defined-how-can-i-use-fs-within-a-vuejs-file

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