简体   繁体   中英

Script output in NodeJS

I have the following code:

app.get('/scr', function(req, res) {
    var command = spawn(scripts + "/script.sh");
    command.stdout.on('data', function (data) {
        res.send(data);
    });
});

The script outputs Hello World! . I would like to have this output on my browser when going to http://localhost:XXXX/scr . However, this wants me to download a file with Hello World! inside. How can I obtain that output on my browser?

It's likely that the data event will be fired multiple times, but send can only be called once. Rather than using send , use write and end ; or, since command.stdout is a stream, just pipe it into the response:

command.stdout.pipe(res);

You may want to explicitly set the MIME type before that, though, eg:

res.type('text/plain');

您需要设置内容类型。

res.set('Content-Type', 'text/plain');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM