我在nodejs中有一个Firebase连接,当连接持久时,它将数据推送到一个url,当它关闭时,我想删除该数据(想想,我推“嘿,我在这里”当我离开的时候,文本消失)在关闭NodeJS时执行操作
我做了一个“可运行”,显示它的一个例子: http://web-f6176e84-c073-416f-93af-62a9a9fbfabd.runnable.com
基本上,按下“Ctrl + C”,并将其打印出“试图删除引用”但从来没有真正删除数据(文档说,remove()相当于set(null),它基本上将数据设置为null,并且由于它为空,所以整个元素应该消失。)
但是,它并没有将其删除,我没有看到数据“消失”。 (我使用的是临时Firebase网址,如果此网址停止存在,您应该使用将与任何可以访问的网址进行复制)。
这是我正在使用的代码。
var FB_URL = 'https://cuhiqgro1t3.firebaseio-demo.com/test_code';
var Firebase = require('firebase');
var myRootRef = new Firebase(FB_URL);
console.log("created Firebase URL");
process.stdin.resume(); //so the program will not close instantly
function delete_fb_entries() {
return function() {
console.log("Trying to remove reference");
myRootRef.remove();
process.exit();
}
}
//do something when app is closing
process.on('exit', delete_fb_entries());
//catches ctrl+c event
process.on('SIGINT', delete_fb_entries());
//catches uncaught exceptions
process.on('uncaughtException', delete_fb_entries());
编辑:作为附加信息的“为什么”,我把我的本地IP地址了我的火力地堡URL,因为我懒,它更容易只是有一个网页的设置,我可以随时访问,将显示(我知道使用路由器表格会更容易些),但实际上我也有其他用途(如果我的在我的网络中发生了,我可以从我的网络中选择一个特定的设备网页和访问我需要的数据,无论哪种方式,它的工作原理,但我不能正确地将其自身删除,这曾经在一个时间点工作,我相信,所以我只能假设API已经改变或某事)。
编辑2:确定删除process.exit()建议,并且runnable似乎删除有问题的数据,我尝试了我的本地数据(和一些清理和注释后),它删除了数据,但是当我按下Ctrl + C时,它不再退出程序..... so yay。
我需要弄清楚“process.exit()”在这一点上是否必要或不必要。编辑3:好,所以我需要使用process.exit(据我所知,Ctrl + C不再退出程序,我必须按Ctrl + Z,然后重新启动)。我试图在之后添加它,但我意识到删除一个firebase元素不是一个同步操作,所以当我关闭它时,我尝试(下一次尝试)是使用remove函数的完整处理程序(remove(onComplete) ,然后将process.exit()添加到onComplete函数中)。
所以最后它看起来像这一点,它似乎与我的应用程序
var FB_URL = 'https://cuhiqgro1t3.firebaseio-demo.com/test_code';
var Firebase = require('firebase');
var myRootRef = new Firebase(FB_URL);
console.log("created Firebase URL");
function onComplete() {
process.exit();
]
process.stdin.resume(); //so the program will not close instantly
function delete_fb_entries() {
return function() {
console.log("Trying to remove reference");
myRootRef.remove(onComplete);
}
}
//do something when app is closing
process.on('exit', delete_fb_entries());
//catches ctrl+c event
process.on('SIGINT', delete_fb_entries());
//catches uncaught exceptions
process.on('uncaughtException', delete_fb_entries());
编辑4工作:针对下面的评论,所以我试图改变一个简单的程序如下所示:
function delete_fb_entries(){
return function() {
console.log("I should quit soon");
}
}
process.stdin.resume(); //so the program will not close instantly
//catches ctrl+c event
process.on('SIGINT', delete_fb_entries());
我的程序从未退出。我不明白为什么节点在这种情况下不会关闭,在console.log之后添加process.exit()会导致nodejs退出。这不是一个异步函数,那么为什么它不在这种情况下退出? (这是一个错误,或者是如何工作由我一个误会?)
为什么'process.exit()',进程已经退出 –
我认为有一段时间我需要它的印象(可能是某个地方的不准确的例子,或者我误解了文档,它只是一些几个月后,我写了这篇文章)。我可以尝试删除它。 – onaclov2000
好,所以我从函数中删除了process.exit(),它似乎在我的例子中工作,但不是在我的本地软件中,现在要弄清楚这是怎么回事。 (我可能更新额外的代码,因为我显示的代码不再重复我最初问到的问题) – onaclov2000