快递 - 为什么代码永远不会返回?

时间:2015-04-27 16:39:12

标签: node.js sqlite express

我是Express新手,并且不明白:为什么以下代码永远不会返回?它似乎挂了。

router.post('/post',function(req,res){

    var file = "test.db"
    var exists = fs.existsSync(file);
    if(!exists) {
        console.log("Creating DB file.");
        fs.openSync(file, "w");
    }
    var sqlite3 = require("sqlite3").verbose();
    var db = new sqlite3.Database(file);

    db.serialize(function() {
        if(!exists) {
            db.run("CREATE TABLE Stuff (thing TEXT)");
        }
        var stmt = db.prepare("INSERT INTO Stuff(thing) VALUES (99999)");
        stmt.finalize();
    });

    db.close();
}); //seems to hang at this line.

1 个答案:

答案 0 :(得分:1)

您需要调用res.send或res.end以从请求中返回内容并防止其挂起。

router.post('/post',function(req,res){

var file = "test.db"
var exists = fs.existsSync(file);
if(!exists) {
    console.log("Creating DB file.");
    fs.openSync(file, "w");
}
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);

db.serialize(function() {
    if(!exists) {
        db.run("CREATE TABLE Stuff (thing TEXT)");
    }
    var stmt = db.prepare("INSERT INTO Stuff(thing) VALUES (99999)");
    stmt.finalize();
});

db.close();
res.send("<h1>Done</h1>");
}); //seems to hang at this line.