Issue with nodeJS Encoding

2019-07-29 10:22发布

问题:

So I'm confronted to a situation that I don't manage to resolve.

Here is my code :

var fs = require('fs');
var path = require('path');

module.exports = {

  showTree: function (req, res) {
    var _p;
    if (req.query.entity) {
      _p = path.resolve(__dirname, '../../uploads/Segmentation', req.query.entity);
    } else {
      _p = path.resolve(__dirname, '../../uploads/Segmentation', 'Default');
    }
    if (req.query.id == 1) {
      processReq(_p, res);
    } else {
      if (req.query.id) {
        _p = req.query.id;
        processReq(_p, res);
      } else {
        res.json(['No valid data found']);
      }
    }

    function processReq(_p, res) {
      var resp = [];
      var encoding = 'utf8';
      fs.readdir(_p,encoding, function(err, list) {
        if (typeof list !== 'undefined'){
          for (var i = list.length - 1; i >= 0; i--) {
            resp.push(processNode(_p, list[i]));
          }
          res.json(resp);
        } else {
          res.json(null);
        }
      });
    }

    function processNode(_p, f) {
      var s = fs.statSync(path.join(_p, f));
      return {
        "id": path.join(_p, f),
        "text": f,
        "icon" : s.isDirectory() ? 'jstree-custom-folder' : 'jstree-custom-file',
        "state": {
          "opened": false,
          "disabled": false,
          "selected": false
        },
        "li_attr": {
          "base": path.join(_p, f),
          "isLeaf": !s.isDirectory()
        },
        "children": s.isDirectory()
      };
    }
  }
};

The problem is with a repository called : "Poste à souder". If I console.log(list[i]) I obtain "Poste a` souder". How can I resolve this encoding issue ?

回答1:

You should specify encoding option to readdir():

var encoding = 'utf8'; // or the encoding you expect...
fs.readdir(_p, {encoding: encoding}, function(err, list) {
  ...
});

Please note that 'utf8' encoding is the default, so you're probably getting a different encoding...

See also the docs.

Second note: server side (node.js) code here on SO code snippet does not work 'as-is'... :-)