Javascript Base64 Nodejs 中的读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28834835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReadFile in Base64 Nodejs
提问by brunocascio
I'm trying to read an image from client side encoded in base64. How to read with nodejs?
我正在尝试从以 base64 编码的客户端读取图像。如何使用nodejs阅读?
My code:
我的代码:
// add to buffer base64 image
var encondedImage = new Buffer(image.name, 'base64');
fs.readFile(encondedImage, "base64", function(err, buffer){
if ( err ) {
console.log('In read file')
console.log(err)
} else {
// check err
lwip.open(buffer, 'jpg', function(err, image){
console.log('in open')
if ( err ) console.log(err)
if ( image ) console.log(image)
// check 'err'. use 'image'.
// image.resize(...), etc.
});
}
})
But, I got this error:
但是,我收到了这个错误:
In read file
[Error: Path must be a string without null bytes.]
回答by Sjoerd
I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
我认为以下示例演示了您需要的内容:http: //www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
The essence of the article is this code part:
文章的精髓就是这个代码部分:
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy.jpg');
回答by Mike Martin
Latest and greatest way to do this:
最新和最好的方法来做到这一点:
const fs = require('fs');
fs.readFileSync('/path/to/file.jpg', { encoding: 'base64' });
回答by Manish Kumar Jaiswal MJ
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);

