简体   繁体   English

在Node.js中从sqlite3数据库构建字符串

[英]Building strings from sqlite3 databse in nodejs

I'd like to write a JS script what works with nodejs and operates on sqlite3 database. 我想写一个与nodejs一起使用并在sqlite3数据库上运行的JS脚本。 The plan is to get data from the database and surrounding with "script" tags. 该计划是从数据库中获取数据并在其周围加上“ script”标签。 My snippet is the following: 我的摘录如下:

var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('/var/www/db/js.sqlite');

var MyRandomCode =
{
    code: "<script>"
}

function appendToCode(snippet) {
    MyRandomCode.code += snippet;
}

function printMe() {
    console.log(MyRandomCode.code);
}

function closeCode() {
    MyRandomCode.code += "</script>";
}

printMe();
randomNode("defun", MyRandomCode);
printMe();
closeCode();

function randomNode(name, MyRandomCode) {
    db.get("SELECT tag_value FROM tags WHERE tag_name=\"" + name + "\"", function(err, rows) {
        if (err) throw err;
        appendToCode(rows['tag_value']);
    });
}

The database only contains a "test" function implementation. 该数据库仅包含“测试”功能实现。 The expected result is: 预期结果是:

<script>
function test() {
    a = 5;
    c += a + b;
    "foo";
    var foo = 5;
    const bar = 6, baz = 7;
    switch ("foo") {
      case "foo":
        return 1;
      case "bar":
        return 2;
    }
    for (var i = 0; i < 5; ++i) {
        console.log("Hello " + i);
    }
    for (var i in [ 1, 2, 3 ]) {
        console.log(i);
    }
    for (var i = 0; i < 5; ++i) console.log("foo");
}
</script>

In spite of this i got 尽管如此,我还是

<script></script>function test() {
    a = 5;
    c += a + b;
    "foo";
    var foo = 5;
    const bar = 6, baz = 7;
    switch ("foo") {
      case "foo":
        return 1;
      case "bar":
        return 2;
    }
    for (var i = 0; i < 5; ++i) {
        console.log("Hello " + i);
    }
    for (var i in [ 1, 2, 3 ]) {
        console.log(i);
    }
    for (var i = 0; i < 5; ++i) console.log("foo");
}

I don't understand why is the order of the strings changed. 我不明白为什么字符串的顺序会更改。 Why isn't the function string inside the "script" tags? 为什么函数字符串不在“ script”标签内?

db.get is an asynch operation, so closeCode will run before the DB operation has finished. db.get是一个异步操作,因此closeCode将在数据库操作完成之前运行。

You should move closeCode and printMe into the async operation so they run after the db update works: 您应该将closeCodeprintMe移到异步操作中,以便它们在数据库更新工作后运行:

function randomNode(name, MyRandomCode) {
    db.get("SELECT tag_value FROM tags WHERE tag_name=\"" + name + "\"", function(err, rows) {
        if (err) throw err;
        appendToCode(rows['tag_value']);
        closeCode();
        printMe();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM