这是我的代码----
var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqvar = (process.env.NSQD_RETH || "localhost:4161").split(",");
var p = r.connect({host:'localhost', port:8080, db:'test', authKey:''});{
p.then(function(conn) {
console.log("Succesfull connection")
}).error(function(error) {
console.log("Error at connection")
})
// Event Reader functionality inside connect callback
var eventreader;
eventreader = new nsq.Reader('hello_topic', 'hello_channel', {
lookupdHTTPAddresses: nsqvar
});
eventreader.connect();
eventreader.on('message', function (msg) {
// Now we have access to the connection
r.table('sprinkle_nsq_test').insert(msg.json()).run(conn);
console.log('Received message [%s]: %s', msg.id, msg.body.toString());
msg.finish();
console.log(msg);
});
}
从终端我试图插入
curl -d '{"id": "712", "name": "Douglas Adams""type "casdasdasomedy"}' 'http://127.0.0.1:4151/put?topic= hello_topic'
在nsq收到消息但是在nodejs程序处显示抛出新错误("消息中的无效JSON"); ^ 错误:消息中的JSON无效
并且同时消息不存储在rethinkdb。
答案 0 :(得分:2)
看起来错误消息是正确的 - 您的JSON
无效。
尝试通过在线JSON validator / viewer复制并粘贴它,它将无效。
我在下面清理过它。希望现在一切正常。
{"id": "712", "name": "Douglas Adams", "type": "casdasdasomedy"}
答案 1 :(得分:1)
您的代码中存在一些错误(至少在RethinkDB方面)。这是一个带注释的固定解决方案(这可能会或可能不会解决您的问题):
var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqvar = (process.env.NSQD_RETH || "localhost:4161").split(",");
// Connect to the client driver port 28015
var p = r.connect({ host:'localhost', port:28015, db:'test' });
p.then(function(conn) {
// Wait until the database is connected
console.log("Succesfull connection");
// Event Reader functionality inside connect callback
var eventreader;
eventreader = new nsq.Reader('hello_topic', 'hello_channel', {
lookupdHTTPAddresses: nsqvar
});
eventreader.connect();
eventreader.on('message', function (msg) {
// Make sure msg.json() is actually valid json
if (typeof msg === 'object' && msg !== null) {
throw new TypeError('`msg` is already and object. It doesnt need to be convert to json');
}
var json = msg.json();
if (typeof json !== 'object' && msg !== null) {
throw new TypeError('`msg.json()` is not an object and cant be inserted into the database.');
}
// Now we have access to the connection
r.table('sprinkle_nsq_test').insert(msg.json()).run(conn)
.then(function () {
// Wait until RethinkDB is done inserted the message to call `.finish`
console.log('Received message [%s]: %s', msg.id, msg.body.toString());
msg.finish();
console.log(msg);
});
});
}).error(function(error) {
console.log("Error at connection to the database");
});