简体   繁体   English

Node.js readFile内容转换为字符串会导致“ ??”

[英]Node.js readFile contents to string results in “??”

var fs = require('fs');
var myNumber = undefined;

function addOne(callback) {
  fs.readFile('./User2.txt', 'utf8', function doneReading(err, fileContents) {
    myNumber = fileContents.toString();
    callback();
  });
}

function logMyNumber() {
  console.log(myNumber);
}

addOne(logMyNumber);

User2.txt only contains one single character, "1". User2.txt仅包含一个单个字符“ 1”。

So when I run it, the output is: "??1". 因此,当我运行它时,输出为:“ ?? 1”。 Why does these question marks appear? 为什么出现这些问号? I originally wanted a number but I just got the message, NaN(not a number, I guess). 我本来想要一个数字,但我只收到消息NaN(我想不是数字)。 So I convert the buffer to a string instead, and got this. 所以我改为将缓冲区转换为字符串,并得到了这个。 Any help? 有什么帮助吗?

It seems you are not the first one with this issue. 看来您不是第一个遇到此问题的人。

Basically you just need to do something like the following: 基本上,您只需要执行以下操作:

fs.readFile(filePath, 'utf8', function (err, fileContents) {
    // Remove BOM character if there is one at the start of the file.
    if(fileContents.charCodeAt(0) == 65279) fileContents = fileContents.substr(1);
}

Here you have many other workarounds taken from that discussion: 在这里,您可以从该讨论中获得许多其他变通方法:

  • Replace: 更换:

    fileContents = fileContents.replace(/^\/, '');

  • Use fs.readFileSync instead of fs.readFile 使用fs.readFileSync代替fs.readFile

  • Use the bomstrip package. 使用bomstrip软件包。

I've fixed it by saving the textfile in wordpad instead of notepad. 我已经通过将文本文件保存在写字板而不是记事本中来修复它。 Saving it as text document - ms-dos format. 将其另存为文本文档-ms-dos格式。

Most of IDE support RegExp search, so it's pretty easy to search for that buggy char in the code base: 大多数IDE支持RegExp搜索,因此在代码库中搜索该错误字符非常容易:

\uFEFF

Just replace it with empty string 只需将其替换为空字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM