Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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  -
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!