我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。


当前回答

退出JS或Node脚本的方法有很多。以下是最相关的:

// This will never exit!
setInterval((function() {  
    return;
}), 5000);

// This will exit after 5 seconds, with signal 1
setTimeout((function() {  
    return process.exit(1);
}), 5000);

// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {  
    return process.kill(process.pid);
}), 5000);

// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {  
    return process.abort();
}), 5000);

如果你在REPL中(即在命令行上运行node之后),你可以输入.exit退出。

其他回答

在我的例子中,我使用window.stop。

window.stop()在当前浏览上下文中停止进一步的资源加载,相当于浏览器中的'stop'按钮。 由于脚本的执行方式不同,此方法不能中断其父文档的加载,但它将停止其父文档的图像、新窗口和其他仍在加载的对象。 用法:window.stop (); (源)

我使用这段代码来停止执行:

throw new FatalError("!! Stop JS !!");

虽然你会得到一个控制台错误,但这对我来说很好。

我知道这是旧的,但如果你想要一个类似的PHP die()函数,你可以这样做:

function die(reason) {
    throw new Error(reason);
}

用法:

console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");

上面的例子只打印“Hello”。

我使用return语句而不是throw,因为throw在控制台给出错误。最好的办法是检查情况

if(condition){
 return //whatever you want to return
}

这只是从这一行停止程序的执行,而不是在控制台中给出任何错误。

这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit