简体   繁体   English

Node.js流困难

[英]Node.js stream difficulties

**Edited: This is the form code I am using currently. **编辑:这是我当前正在使用的表单代码。 I basically took it 我基本上接受了
from suggestions on stack overflow. 从堆栈溢出的建议。

    app.post('/FunFun.js', function(req, res) {
    var file = req.params.value; 
console.warn(req.params);
console.warn(req.params.value);
    var fileContent = JSON.stringify(file);


    fs.appendFile('Focus.txt', fileContent + '\n', function(err) {
    if (err) {
        console.log('Failed to append to the file! ', err)
    } else {
        console.log('Appended data to file!');
    }
    res.render('Form.html');

     });
     });

So, I am trying to basically read form values from a survey(multiple choice) I created with HTML into a Stream in my Node.js file in order to save the values of each participant in a txt file( I know a database is preferable, this is for college). 因此,我试图从我使用HTML创建的调查(多选)中基本上读取表单值到Node.js文件中的Stream中,以便将每个参与者的值保存在txt文件中(我知道最好使用数据库,这是针对大学的)。 So here is my Node.js file: 所以这是我的Node.js文件:

var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs');
var bodyParser = require('body-parser');
var engines = require('consolidate');

app.set('views', __dirname + '/Desktop');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));


app.get('/', function(reg, res) {
    res.render('Form.html');
});

app.post('/FunFun.js', function(req, res) {
    res.render('Form.html');
    var file = req.body; //req.params.values;
    filecontent = JSON.stringify(file);

    var stream = fs.createWriteStream("Focus.txt", {
        objectMode: true
    }); //{'flags': 'a'});
    stream.on('open', function() {
        stream.write(filecontent);
        stream.end();
    });
});

var server = app.listen(8080, function() {
    console.log('Server listening on port 8080');
});

I would post my form, but it is a standard multiple choice questionnaire type form with radio buttons. 我会发布表格,但这是带有单选按钮的标准多选问卷类型表格。 Anyways, I want to save the users choice in a file, and to me it seems that my NOde.js file should do the trick, but I keep getting this error: 无论如何,我想将用户的选择保存在一个文件中,对我来说,我的NOde.js文件似乎可以解决问题,但是我仍然收到此错误:

TypeError: Invalid non-string/buffer chunk

So I know that streams apparently cannot usually handle data other than strings and buffers. 因此,我知道流显然不能处理字符串和缓冲区以外的数据。 However, I thought JSON.stringify would do the trick. 但是,我认为JSON.stringify可以解决问题。 However, it isn't. 但是,事实并非如此。 I am new to Node.js and express, so wondering if anyone has any ideas on what I am missing? 我是Node.js的新手并表示,所以想知道是否有人对我缺少的内容有任何想法吗?

Xtra: Decided to show a sample of my HTML form just for emphasis. Xtra:决定显示我的HTML表单的示例只是为了强调。 I am trying to extract the value of the radio button selected. 我正在尝试提取所选单选按钮的值。

   <form  action = "/FunFun.js" method = "post" style = "border : 2px   
    solid black;">
 .......

<table>
    <tr>
        <td colspan="1">7</td>
        <td colspan="8">If I had more time, I would have done better in this course.</td>
        <td colspan="16">
            <table style="width: 100%;">
                <tr>
                    <td><input id="g1" name="GroupG" onclick="groupG()" type="radio" value="1std"></td>
                    <td><input id="g2" name="GroupG" onclick="groupG()" type="radio" value="1sod"></td>
                </tr>
            </table>
        </td>
        <td><input id="g3" name="GroupG" onclick="groupG()" type="radio" value="1neu"></td>
        <td colspan="16">
            <table style="width: 100%;">
                <tr>
                    <td><input id="g4" name="GroupG" onclick="groupG()" type="radio" value="1sta"></td>
                    <td><input id="g5" name="GroupG" onclick="groupG()" type="radio" value="1soa"></td>
                </tr>
            </table>
        </td>
    </tr>
</table>

.....
<td colspan = 100%> <input type="submit" value="submit" formaction 
  = "/FunFun.js"> <input type="reset" onClick = "resetB()">   </td>

</tr>


</table>

If you take a look at the documentation for fs.createWriteStream , you'll see that there is no objectMode in the valid options. 如果查看fs.createWriteStream的文档,您会发现有效选项中没有objectMode objectMode is not documented, because even though the underlying stream.Writable class does support the feature, the fs.WriteStream does not. 没有记录objectMode ,因为即使基础stream.Writable类确实支持该功能, fs.WriteStream也不支持。 For a good reason - how would it choose how to serialize the objects you've given it? 有一个很好的理由-它会如何选择如何序列化您赋予它的对象? How should it represent { a:1 } ? 它应如何表示{ a:1 } In textual JSON? 使用文字JSON? In some binary format? 以某种二进制格式? Exactly. 究竟。 That's up to the programmer to choose. 这由程序员选择。

Additionally, the POST handler is writing a response to the client (in HTML) before actually appending to the file ( res.render(...) ). 另外,POST处理程序在实际附加到文件( res.render(...) )之前,先将响应写入HTML(以HTML格式)给客户端。 I would suggest moving this to the success callback of the write, so that you actually do the operation before returning results. 我建议将其移至写入的成功回调,以便在返回结果之前实际执行该操作。

So, remove the objectMode from the options and move the res.render(...) and the write works. 因此,从选项中删除objectMode并移动res.render(...)并进行写入。 Remember that when working with streams which do not operate in object mode, you can only write strings, Buffer s or Uint8Array s , so you're correct in using JSON.stringify first. 请记住,当使用不能在对象模式下运行的流时,只能写字符串, BufferUint8Array ,因此首先使用JSON.stringify是正确的。

By the way, unless you're streaming directly from the client to the file, which would probably require you to stream the JSON transform on the fly somehow, you'd probably be better off using fs.appendFile or fs.writeFile . 顺便说一下,除非您直接从客户端流式传输到文件,否则可能需要以某种方式即时流式传输JSON转换,否则最好使用fs.appendFilefs.writeFile They have a simpler API which I think you might want: 他们有一个更简单的API,我想您可能想要:

app.post('/FunFun.js', function(req, res) {
    var file = req.body; // req.params.values;
    var fileContent = JSON.stringify(file);

    fs.appendFile('Focus.json', fileContent + '\n', function(err) {
        if (err) {
            console.log('Failed to append to the file! ', err)
        } else {
            console.log('Appended data to file!');

        }
        res.render('Form.html')
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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