Special characters in node.js readdir()

邮差的信 提交于 2019-12-11 11:34:34

问题


I'm running this piece of code in node.js in order to see the files in a directory an to see the stats for them:

var getFiles = function (dir, done) {
  fs.readdir(dir, function (err, files) {
    if (err) return done(err);
    var pending = files.length;
    files.forEach(function (file) {
      fullPath = dir + "/" + file;
      console.log(fullPath);
      fs.stat(fullPath, function (err, stat) {
        if (err) {
          console.log("Stat error");
        } else if (stat && stat != undefined) {
          console.log("Success");
        }
      });
    });
  });
}

My problem is with file names containing special characters. I'm swedish, so there are lots of å, ä and ö. The output from fullPath is correct when it's outputting most filenames, but whenever the filename contains a special character, that character is displayed as "?", and then fs.stat fails cause it cannot find the file. What have I missed? I'm running version v0.5.7 on Windows.
Thanks in advance.


回答1:


I think that the problem is that Windows encodes filenames as ISO-whatever but node reads them as utf8. Try using iconv to convert from iso to utf8.



来源:https://stackoverflow.com/questions/7738430/special-characters-in-node-js-readdir

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