嗨,我正在编写一个简单的 nodejs 推送通知服务器,它基本上是读取动态编辑的 json 文件并将其内容推送到客户端。
更新:如果我删除类似的数据 = JSON.parse(data); 有人可以澄清一下吗?
我每 5 秒使用 python 编辑一次 json 文件。但是每次我运行 python 循环来编辑文件时,节点服务器都会崩溃。但是,如果我在 while 循环中单独运行相同的代码,节点服务器就可以正常工作。
节点服务器出现以下错误
debug - cleared heartbeat timeout for client c_u5Oi1eGnwaDerGREMD
debug - set heartbeat interval for client c_u5Oi1eGnwaDerGREMD
{"sample": {"name": "Shubhanshu Mishra100", "networks": ["facebook", "twitter",
"linkedin"]}}
debug - websocket writing 5:::{"name":"notification","args":[{"sample":{"name
":"Shubhanshu Mishra100","networks":["facebook","twitter","linkedin"]},"time":"2
012-10-09T11:24:55.588Z"}]}
{"sample": {"name": "Shubhanshu Mishra100", "networks": ["facebook", "twitter",
"linkedin"]}}
debug - websocket writing 5:::{"name":"notification","args":[{"sample":{"name
":"Shubhanshu Mishra100","networks":["facebook","twitter","linkedin"]},"time":"2
012-10-09T11:24:55.589Z"}]}
{"sample": {"name": "Shubhanshu Mishra200", "networks": ["facebook", "twitter",
"linkedin"]}}
debug - websocket writing 5:::{"name":"notification","args":[{"sample":{"name
":"Shubhanshu Mishra200","networks":["facebook","twitter","linkedin"]},"time":"2
012-10-09T11:25:00.598Z"}]}
{"sample": {"name": "Shubhanshu Mishra200", "networks": ["facebook", "twitter",
"linkedin"]}}
debug - websocket writing 5:::{"name":"notification","args":[{"sample":{"name
":"Shubhanshu Mishra200","networks":["facebook","twitter","linkedin"]},"time":"2
012-10-09T11:25:00.619Z"}]}
undefined:0
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at F:\My Codes\NodeJs\PushNotification\server.js:25:16
at fs.readFile (fs.js:176:14)
at Object.oncomplete (fs.js:297:15)
我正在使用 Node.js 中的以下代码读取 response.json 文件
io.sockets.on('connection', function(socket){
fs.watch('response.json', function(curr, prev){
fs.readFile('response.json', 'utf8', function(err, data){
if(err) throw err;
console.log(data);
data = JSON.parse(data);
data.time = new Date();
socket.volatile.emit('notification', data);
});
});
});
更新:如果我删除类似的数据 = JSON.parse(data); 有人可以澄清一下吗?
当我单独调用我的python脚本时,我的python代码是:
import json
import time
jsonStr = {
"sample": {
"name": "Shubhanshu Mishra",
"networks": [
"facebook",
"twitter",
"linkedin"
]
}
}
i = 0
jsonStr['sample']['name'] = "Shubhanshu Mishra" + str(i);
fStr = json.dumps(jsonStr)
with open('response.json', 'w') as f:
f.write(fStr)
f.closed
但是,当我将上面的相同代码包装在一个睡眠时间为 5 秒的 while 循环中时,我得到了上述错误。我的 while 循环代码是:
while True:
i += 100
print i
jsonStr['sample']['name'] = "Shubhanshu Mishra" + str(i);
fStr = json.dumps(jsonStr)
#f = open("response.json", "w")
with open('response.json', 'w') as f:
f.write(fStr)
f.closed
#f.write(fStr)
print "Written to file: " + fStr
#f.close()
time.sleep(5)