1

I'm trying to pipe Express request object to a writable stream. NodeJS creates a file, but it's empty. What am I missing?

var express = require('express');
var fs = require('fs');

var app = express();
    app.use(middleWare);
    app.listen(3000);

function middleWare(req, res, next){
    var ws = fs.createWriteStream('./test.txt');
    req.pipe(ws);
    res.sendStatus(200);
}

When I replace req.pipe(ws) with ws.write(req) I get an error:

 TypeError: Invalid non-string/buffer chunk

When I replace ws.write(req) with ws.write(JSON.stringify(req)) I get an error:

  TypeError: Converting circular structure to JSON
manidos
  • 3,244
  • 4
  • 29
  • 65
  • This is a very unusual thing to do, `req` object is not generally meant to be written to a file. What are you actually trying to do by this? – laggingreflex Apr 17 '16 at 13:40
  • @laggingreflex, I want to have a closer look at the request object structure. I can't do this in console, because the output exceeds the maximum and I can't scroll to the very top. – manidos Apr 17 '16 at 13:44
  • [console.dir or util.inspect can show greater depths](http://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-js-console-log-rather-than-object/27534731#27534731) but [node debugger with chrome inspector might be more helpful](https://mattdesl.svbtle.com/debugging-nodejs-in-chrome-devtools). – laggingreflex Apr 17 '16 at 13:52
  • @laggingreflex, Thank you! I ended up using console.dir! – manidos Apr 17 '16 at 14:14

1 Answers1

0

You can only write a string or buffer to a file.

When you try to convert the object to a string with JSON.stringify(), you get an error because the object contains circular references, which is not allowed, and the reason why you cannot use this function.

You could try to convert the object to JSON, before converting it to a string.

But you could also try to extract only the relevant fields of the request and save them to the file, after converting them to a string.

Community
  • 1
  • 1
piscator
  • 8,028
  • 5
  • 23
  • 32
  • Thank you! I've used an NPM module [CircularJSON](https://github.com/WebReflection/circular-json) for conversion. Everything works just fine! – manidos Apr 17 '16 at 14:11