我使用下面的代码将文件编码为 base64。
var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
Run Code Online (Sandbox Code Playgroud)
我认为在文件中我们有问题“”和‘’字符,但没关系"
当我们有It’s, node 对字符进行编码时,但是当我解码时,我将其视为
It’s
这是我用来解码的javascript:
fs.writeFile(reportPath, body.buffer, {encoding: 'base64'}
Run Code Online (Sandbox Code Playgroud)
因此,一旦文件被编码和解码,这些时髦的字符就无法使用了—— It’s
任何人都可以对此有所了解吗?
这应该有效。示例脚本:
const fs = require('fs')
const filepath = './testfile'
//write "it's" into the file
fs.writeFileSync(filepath,"it's")
//read the file
const file_buffer = fs.readFileSync(filepath);
//encode contents into base64
const contents_in_base64 = file_buffer.toString('base64');
//write into a new file, specifying base64 as the encoding (decodes)
fs.writeFileSync('./fileB64',contents_in_base64,{encoding:'base64'})
//file fileB64 should now contain "it's"
Run Code Online (Sandbox Code Playgroud)
我怀疑你的原始文件没有 utf-8 编码,看你的解码代码:
fs.writeFile(reportPath, body.buffer, {encoding: 'base64'})
我猜您的内容来自某种 http 请求,因此内容可能不是 utf-8 编码的。看看这个:https : //www.w3.org/International/articles/http-charset/index如果没有指定字符集 Content-Type text/ 使用 ISO-8859-1。
这是有帮助的代码。
\n\nvar bitmap = fs.readFileSync(file);\n\n// Remove the non-standard characters\nvar tmp = bitmap.toString().replace(/[\xe2\x80\x9c\xe2\x80\x9d\xe2\x80\x98\xe2\x80\x99]/g,'');\n\n// Create a buffer from the string and return the results\nreturn new Buffer(tmp).toString('base64');\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7337 次 |
| 最近记录: |