Matthias
Matthias

Reputation: 707

Read and echo image file Node.js

I have a small png file called small.png. I expect the following Node.js code to be equivalent to a cat of the file. However, I am clearly reading something incorrectly, as the result is different, and redirecting output into a new file results in something that is not even recognizable as a PNG.

node -e 'console.log(require("fs").readFileSync("static/small.png", "utf8").toString())'

Or, expanded:

const fs = require("fs");
console.log(fs.readFileSync("static/small.png").toString());

I suspected it could be an encoding issue, but "utf16le" seemed to look less like the original.

Upvotes: 0

Views: 375

Answers (1)

Matt
Matt

Reputation: 74761

A binary file can't be reproduced as a utf8 string, unless maybe if it happens to be a utf8 string in the first place.

fs.createReadStream defaults to no encoding and can be piped to the stdout of the node process.

const stream = require("fs").createReadStream("small.png")
stream.pipe(process.stdout)
% cat small.png | sha256sum
065453ee61387cec8383a2337c488a3f65e709f52637efd5f97c1efe6c333f2b  -

% node -e 'st = require("fs").createReadStream("small.png"); st.pipe(process.stdout)' | sha256sum
065453ee61387cec8383a2337c488a3f65e709f52637efd5f97c1efe6c333f2b  -

Upvotes: 1

Related Questions