how can i write a string data using fs

38 views
Skip to first unread message

jo...@amt.in

unread,
May 11, 2017, 7:19:26 PM5/11/17
to nodejs

When I sending the following request ,

var request = require('request');
var fs = require("fs");    
var headers = {
'Authorization': 'Bearer cEet0ordwd4VsUHi9jnbQuWIY+fL5RKeSGP65HEbGtGznHQ4XOaOwaTDQqwLT0bI24oFKLtMvspYvPgi4qR3Bv1oMQp+Wak2x7TRSxsL/oqQN1kIzaWVcGTk9aK4ICxU6qK4tM0KHoAkjA1ahEJSswdB04t89/1O/w1cDnyilFU='
};

var options = {
headers: headers
};
var r=request(options );
r.pipe(fs.createWriteStream('./m10.wav' ));
in here the type of the request is an object.
Now the file I can open with a music player. But when I writing the body of the request like,

request(options,function (err,res,body){
var p=body;
p.pipe(fs.createWriteStream('./m10.wav' ));
})
in here the type of body is string.
I can't open the file. It shows error. How can I write this file and When I checking the type of both responce first one is an object type and second once is a string type. Any problem for writing string data using fs?

Zlatko

unread,
May 19, 2017, 11:28:46 PM5/19/17
to nodejs
Few things, one really important:

You shared your API token with the world!

If you can, delete that token and in the future, replace it with a placeholder when you're posting examples.

Second, request you can handle errors in streams, e.g.

    request(options).pipe(fs.createWriteStream(filename)).on('error', err => console.log(err));

However, this is only a part of the solution - the problem is that request doesn't think that e.g. 404 response will be an error - it'll let you handle it. Check this answer: http://stackoverflow.com/a/14972828/162070

What it says is to check for the status code before creating your write stream, something like this:

    const r = request(url)
    r.on('response', function (resp) {
      if (resp.statusCode > 399) { // e.g. 400, 404 or whatever else you consider failure
        throw new Error();
      }   
      r.pipe(new WritableStream())
    });


Reply all
Reply to author
Forward
0 new messages