Created
October 17, 2017 18:19
-
-
Save spelcaster/df54b0168fd1ac883313259a92cc9e44 to your computer and use it in GitHub Desktop.
Read a file synchronously and parse it to base64 using the builtin Buffer class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
const gMinLength = 3; | |
const gFile = '/tmp/test'; | |
const gEncoding = 'ascii'; | |
function sample1() { | |
var data = fs.readFileSync(gFile); | |
var buff = Buffer.from(data, gEncoding); | |
return buff.toString('base64'); | |
} | |
function sample2() { | |
var buff = new Buffer(0); | |
var buffSize = gMinLength * 24; | |
var fd = fs.openSync(gFile, 'r'); | |
var length = 0; | |
var buffer = new Buffer(buffSize); | |
// could be better? | |
while (true) { | |
var num = fs.readSync(fd, buffer, 0, buffSize, length); | |
if (!num) { | |
break; | |
} | |
var newBuffLength = buff.length + num; | |
buff = Buffer.concat([buff, buffer], newBuffLength); | |
length += num; | |
} | |
return buff.toString('base64'); | |
} | |
console.log(sample1()); | |
console.log(sample2()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment