fs.readFile 不是函数 MQTT 证书

fs.readFile is not a function MQTT certificates

我正在尝试读取证书以通过 js 和 node.js 访问我的 Mqtt 代理。但是我收到以下错误:fs.readFile 不是函数。

我注意到 fs 在 npm 包中似乎已被弃用,所以我尝试使用 graceful-fs 和 fs-extra 但它导致我遇到类似的错误。我也试过更改 require to 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"
  ]
}

感谢您的帮助

fs.readFile 需要 3 个参数。 fs.readFile('fileName', 'utf8', function) 这里的函数是回调函数,用来处理错误或者获取需要的数据。 你可以试试这个:-

var caFile = fs.readFile('myCApath.txt', 'utf8', function(err, data){
    if(err){
       console.log(err);
    }else{      
      return data; 
    }
});

如果你想忽略第二个参数那么你可以忽略,但是我推荐使用encoding.

已编辑 - 或者您可以尝试使用 fs.readFileSync( path, options )

fs.readFile 是异步函数,这意味着你需要在回调函数中尝试连接。否则变量 caFilecertFilekeyFile 程序读取为 undefined

你可以这样使用Promise

import Mqtt from 'mqtt';
const fs = require('fs')

const read = (path, type) => new Promise((resolve, reject) => {
  fs.readFile(path, type, (err, file) => {
    if (err) reject(err)
    resolve(file)
  })
})

Promise.all([read('myCApath', 'utf8'), read('myCERTpath', 'utf8'), read('myKEYpath', 'utf8')]).then((arr) => {
  const client = Mqtt.connect({host: 'adress', port:'1884', username:'username',password:'passwd', ca: arr[0]});
});

另一种使用回调的方法

import Mqtt from 'mqtt';
const fs = require('fs');

var caFile = fs.readFile("myCApath", "utf-8", function() {
  var certFile = fs.readFile("myCERTpath", "utf-8", function() {
    var keyFile = fs.readFile("myKEYpath", "utf-8", function() {
      const client = Mqtt.connect({host: 'adress', port:'1884', username:'username',password:'passwd', ca: caFile});
    })
  })
})

使用fs.readFileSync(path)docs

import Mqtt from 'mqtt';
const fs = require('fs');
var caFile = fs.readFileSync("myCApath")
var certFile = fs.readFileSync("myCERTpath")
var keyFile = fs.readFileSync("myKEYpath")
const client = Mqtt.connect({host: 'adress', port:'1884', username:'username',password:'passwd', ca: caFile});

结束我自己在 hardillb 的评论中回答的问题:

"您无法从浏览器访问文件(您也无法在浏览器中为 MQTT 客户端设置证书,因为所有证书处理都由浏览器完成,用于 WebSocket 连接)"