【发布时间】:2021-12-30 04:39:55
【问题描述】:
我正在尝试读取证书以通过 js 和 node.js 访问我的 Mqtt 代理。但是我收到以下错误:fs.readFile 不是函数。
我注意到 fs 在 npm 包中似乎已弃用,因此我尝试使用 graceful-fs 和 fs-extra,但它导致了类似的错误。我也尝试将 require 更改为 import 但它没有改变任何东西。
这是我的代码:
import Mqtt from 'mqtt';
const fs = require('fs');
var caFile = fs.readFile("myCApath")
var certFile = fs.readFile("myCERTpath")
var keyFile = fs.readFile("myKEYpath")
const client = Mqtt.connect({host: 'adress', port:'1884', username:'username',password:'passwd', ca: caFile});
这是我的 package.json
{
"name": "frontend",
"version": "0.0.9",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"axios": "^0.19.0",
"element-ui": "^2.11.1",
"leaflet": "^1.5.1",
"mqtt": "^3.0.0",
"start": "^5.1.0",
"vue": "^2.6.10",
"vue-router": "^3.1.2",
"vuex": "^3.1.1"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^3.10.0",
"@vue/cli-plugin-eslint": "^3.10.0",
"@vue/cli-service": "^3.10.0",
"@vue/eslint-config-airbnb": "^4.0.1",
"babel-eslint": "^10.0.2",
"babel-plugin-component": "^1.1.1",
"eslint": "^6.2.0",
"eslint-plugin-vue": "^5.2.3",
"vue-cli-plugin-element": "^1.0.1",
"vue-template-compiler": "^2.6.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"@vue/airbnb"
],
"rules": {
"import/extensions": [
"error",
"always",
{
"js": "never",
"vue": "never"
}
],
"no-param-reassign": [
"error",
{
"props": true,
"ignorePropertyModificationsFor": [
"state",
"acc",
"e",
"s"
]
}
],
"max-len": [
"off"
],
"vue/no-unused-vars": [
"off"
]
},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
感谢您的帮助
【问题讨论】:
-
该代码到底在哪里运行?错误是来自 NodeJS 应用程序还是来自浏览器端?
-
我在 Spring Boot 应用程序中运行此代码,然后在浏览器控制台中出现错误,浏览器返回空白页
-
好的,你不能从浏览器访问文件(你也不能在浏览器中为MQTT客户端设置证书,因为所有的证书处理都是由浏览器完成WebSocket连接的)
-
哦,好的,谢谢,那你知道我怎样才能让我的前端和mqtt通信吗?
-
这是一个完全不同的问题,您的问题中没有足够的细节来正确回答。但是基于 Websockets 的 MQTT 工作得很好,但是浏览器需要信任用于预先签署证书的 CA。
标签: javascript mqtt fs