0

in php we can write the binary string into an image file by using this

$binary = hex2bin($hex);
file_put_contents("myphoto.png", $binary);

it uses the file_put_contents in order to Write it to disk:

in node.js how can we achieve this like the file_put_contents. ?

EDIT: I tried this as suggested by the comments but it gives me an error

 var binarydata = fs.readFileSync('mybin.txt',{flag:'w'});

        fs.writeFileSync( 'myphoto.png', binarydata );


Error: EPERM, operation not permitted
    at Error (native)
    at Object.fs.readSync (fs.js:552:19)
    at Object.fs.readFileSync (fs.js:389:28)

Thank you in advance.

3
  • 1
    Reading the documentation for the fs (file system) module would be a good place to start. Commented May 4, 2015 at 18:18
  • something like fs.writeFileSync() and making sure what you are writing is a Buffer type Commented May 4, 2015 at 18:19
  • @Catalyst, can you show me some snippet please Commented May 4, 2015 at 18:24

1 Answer 1

4

This should work for you:

var fs = require( 'fs' );
var wstream = fs.createWriteStream( 'myphoto.jpg' );
wstream.write( $binary );
wstream.end();

Here is the documentation for node.js fs-module: https://nodejs.org/api/fs.html

If you want to do something when it has finished use

fs.writeFileSync( 'myphoto.png', $binary );

or do it asynchronous:

var fs = require('fs');
var wstream = fs.createWriteStream('myphoto.jpg');
wstream.on( 'finish', function() {
    // do something
});
wstream.write( $binary );
wstream.end();

Read file and write to another file:

var fs = require('fs');
fs.readFile( 'temp.txt', function( err, data ) {
    if (err) throw err;

    var wstream = fs.createWriteStream( 'myphoto.jpg' );
    wstream.on( 'finish', function() {
        // do something
    });
    wstream.write( data );
    wstream.end();
});

Edit: My code was working all time, it just has to be 'myphoto.jpg' instead of 'myphoto.png' ;) So the solution isn't to do it like this, you just have to rename the file:

var fs = require('fs');
fs.renameSync( 'temp.txt', 'myphoto.jpg' );

or if you need your temp.txt, then copy it like this:

var fs = require('fs');
fs.createReadStream( 'temp.txt' ).pipe( fs.createWriteStream( 'myphoto.jpg' ) );
Sign up to request clarification or add additional context in comments.

7 Comments

my binary data is stored in a file temp.txt,how can I get it first ?
Please read the documentation... fs.readFileSync( 'temp.txt' ); I'll also edit my post to add an asynchronous codesnippet to my post, then you should know all you need
Error: EPERM, operation not permitted
Do you use Linux? Then start node with sudo
im in windows...I tried your code. but the image cannot be open
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.