Невозможно получить новые значения из базы данных SQLite с помощью Node.js - PullRequest
0 голосов
/ 01 июня 2019

Я использую Node.js вместе с SQLite3 для связи с моей базой данных. Я могу успешно добавлять новые данные и читать существующие данные. Моя проблема в том, что я не могу получить данные, которые добавляю через интерфейс, если я не перезагружаю свой сервер Node.js.

Я понимаю, что база данных, вероятно, заблокирована, или необходимо изменить функции для перечитывания новых данных, но я просто не могу на всю жизнь понять, как.

Прошу прощения за код, он предназначен для отслеживания того, сколько молока было сцежено с течением времени, и составляет график.

server.js


    var express = require('express')
    var tempstats = require('./db.js')
    var path = require('path')
    var app = express()
        // var db = require('./db.js')
    var sqlite3 = require('sqlite3')
    var db = new sqlite3.Database('web-app.db')

    var publicPath = path.resolve(__dirname, "public");
    app.use(express.static(publicPath));

    // Parse URL-encoded bodies (as sent by HTML forms)
    app.use(express.urlencoded());

    // Parse JSON bodies (as sent by API clients)
    app.use(express.json());

    // All general page links should be listed below
    app.get("/", function(request, response) {
        response.sendFile("/index.html", {});
    });
    // Access the parse results as request.body
    app.post('/', function(request, response) {
        console.log(request.body.user.leftBrest);
        console.log(request.body.user.rightBrest);
        db.run('INSERT INTO milk VALUES (NULL, ?, ?, CURRENT_TIMESTAMP)', [request.body.user.leftBrest, request.body.user.rightBrest], function(err) {
            if (err) {
                console.log("There's another error!" + err.message);
            } else {
                console.log('Record successfully added with id: ' + this.lastID);
                response.sendFile(__dirname + "/public/index.html");
            }
        });
    });

    // SQL data interaction functions from db.js
    app.get('/left', function(req, res) {
        res.send(tempstats.lastAmountLeft + '')
        console.log(tempstats.lastAmountLeft + '')
    })
    app.get('/right', function(req, res) {
        res.send(tempstats.lastAmountRight + '')
        console.log(tempstats.lastAmountRight + '')
    })

    app.get('/selectedTemp', function(req, res) {
        res.send(tempstats.selectedTemp + '')
    })


    // Json testing sendfile is different to sendFile
    app.get('/json', function(req, res) {
        res.sendfile('./test.json', {})
    })

    // 4xx Errors are served from here
    // app.use(function(req, res) {
    //     res.status(404)
    //     res.render('404.html', {
    //         urlAttempted: req.url
    //     })
    // })

    // Server listen code
    var port = 3000
    app.listen(port, function() {
        console.log('The server is listening on port ' + port)
    })

db.js

lastAmountLeft и LastAmountRight необходимо обновить, но не нужно. (Я также использую их значения внутри моей HTML-страницы)


    'use strict'

    var sqlite3 = require('sqlite3')
        // var db = new sqlite3.Database('web-app.db')
    let db = new sqlite3.Database('web-app.db', (err) => {
        if (err) {
            return console.error(err.message);
        }
        console.log('Connected to the in-memory SQlite database.');
    });

    const tempstats = {}


    db.each('SELECT * FROM milk WHERE rowid = 3', function(err, row) {
        if (err) {
            console.log('Oh no!' + err.message);
        } else {
            console.log('Row ID: ' + row._id + " shows the left breast had an expressed volume of: " + row.left + "ml")
            tempstats.specificAmountLeft = row.left;

        }
    })

    db.get('SELECT * FROM milk WHERE date order by date desc limit 1', function(err, row) {
        if (err) {
            console.log('Oh no!' + err.message);
            return;
        }

        console.log(row)

        console.log("The last expressed volume from the left breast was: " + row.left + "ml")
        tempstats.lastAmountLeft = row.left;


    })

    db.get('SELECT * FROM milk WHERE date order by date desc limit 1', function(err, row) {
        if (err) {
            console.log('Oh no!' + err.message);
            return;
        }

        console.log(row)

        console.log("The last expressed volume from the right breast was: " + row.right + "ml")
        tempstats.lastAmountRight = row.right;


    })
    module.exports = tempstats
        // module.exports = db

1 Ответ

0 голосов
/ 02 июня 2019

Ответ на самом деле был довольно простым, я не могу поверить, что пропустил его. Я просто обернул свои функции «lastAmountLeft» и «lastAmountRight» в setInterval и вызываю его каждые X секунд. Моя страница теперь обновляется с последними данными.


    setInterval(function() {
        db.get('SELECT * FROM milk WHERE date order by date desc limit 1', function(err, row) {
            if (err) {
                console.log('Oh no!' + err.message);
                return;
            }

            console.log(row)

            console.log("The last expressed volume from the right breast was: " + row.right + "ml")
            tempstats.lastAmountRight = row.right;


        })
    }, 1000)

...