Search code examples
javascripthtmlnode.jssqlitenode-sqlite3

How to use document.querySelector and require with node.js and SQLite3


So pretty much I am trying to create an application that interacts with a database but cannot seem to get either one to work. Either the require causes an issue or the document keyword does (dependant on which I start from) I was just wondering if anyone knew a fix to this? I was trying to use classes and methods so I could split up the files as well but just doesnt want to work

I am very open to using another library or framework if need be so if you have any recommendations please let me know.

Here is my main.js

'use strict'

const handleSQLite = require('./handleSQLite.js')

let db = new handleSQLite();

db.openDatabase();



document.querySelector('.search').addEventListener('click', function() {
    document.querySelector('.search-sec').classList.remove('hidden');
    document.querySelector('.insert').classList.add('hidden');
    document.querySelector('.remove').classList.add('hidden');
    document.querySelector('.btns').classList.add('bts-search-clicked');
    document.body.style.backgroundColor = "#FFB3E9";
    //document.querySelector('.insert').classList.add('.search-clicked');
    //document.querySelector('.insert').style.position = 'absolute';
    //document.querySelector('.insert').style.bottom = '-500px';
    console.log('search clicked');
});

document.querySelector('.insert').addEventListener('click', function() {
    document.querySelector('.insert-sec').classList.remove('hidden');
    document.querySelector('.search').classList.add('hidden');
    document.querySelector('.remove').classList.add('hidden');
    document.querySelector('.btns').classList.add('bts-insert-clicked');
    document.body.style.backgroundColor = "#BAE1C4";
    console.log('insert clicked');
});

// Remove Button Controller
document.querySelector('.remove').addEventListener('click', function() {
    //document.querySelector('.insert-sec').classList.remove('hidden');
    document.querySelector('.search').classList.add('hidden');
    document.querySelector('.insert').classList.add('hidden');
    document.querySelector('.btns').classList.add('bts-remove-clicked');
    document.body.style.backgroundColor = "#BAE1FF";
    console.log('remove clicked');
});

Here is my server.js

const http = require('http');
//const path = require("path");
//const express = require('express');
const fs = require('fs');
const port = 8080;
//const app = new express();
//app.use(express.static(__dirname+'./public'));



// Open Server
const server = http.createServer(function(req, res) {
    
    // Handle main page request
    if (req.url === '/'){
        res.writeHead(200, { 'Content-Type': 'text/html'})
        fs.readFile('index.html', function(error, data) {
            if (error) {
                res.writeHead(404);
                res.write('Error: File Not Found');
            } else {    
                res.write(data);
            }
            res.end();
        })
    }

    // Handle stylesheet request
    else if (req.url === '/style.css') {
        res.writeHead(200, { 'Content-Type': 'text/css'})
        fs.readFile('style.css', function(error, data) {
            if (error) {
                res.writeHead(404);
                res.write('Error: File Not Found');
          } else {
              res.write(data);
          }
          res.end();
        })
    }

    // Handle Javascript request
    else if (req.url === '/main.js') {
        res.writeHead(200, { 'Content-Type': 'text/javascript'})
          fs.readFile('main.js', function(error, data) {
                if (error) {
                    res.writeHead(404);
                    res.write('Error: File Not Found');
              } else {
                  res.write(data);
              }
              res.end();
        })
    }

    // Handle image request
    else if (req.url === '/img/search.png') {
        res.writeHead(200, { 'Content-Type': 'image/png'})
          fs.readFile('img/search.png', function(error, data) {
                if (error) {
                    res.writeHead(404);
                    res.write('Error: File Not Found');
              } else {
                  res.write(data);
              }
              res.end();
        })
    }

    // Handle SQL request
    else if (req.url === '/handleSQLite.js') {
        res.writeHead(200, { 'Content-Type': 'text/javascript'})
          fs.readFile('handleSQLite.js', function(error, data) {
                if (error) {
                    res.writeHead(404);
                    res.write('Error: File Not Found');
              } else {
                  res.write(data);
              }
              res.end();
        })
    }

    // Handle database request
    else if (req.url === './db/storage.db') {
        res.writeHead(200, { 'Content-Type': 'text/plain'})
          fs.readFile('./db/storage.db', function(error, data) {
                if (error) {
                    res.writeHead(404);
                    res.write('Error: File Not Found');
              } else {
                  res.write(data);
              }
              res.end();
        })
    }


    
});


// Open the port to listen to
server.listen(port, '172.16.1.80' || 'localhost', function(error) {
    if (error) {
        console.log('Something went wrong', error);
    } else {
        console.log('Server is listening on port ' + port);
    }
});

And here is my handleSQLite.js I know this one is very messy, I have just been trying tons of things

const sqlite3 = require('sqlite3');

/*
const searchInput = document.getElementById('search-input');
const matchList = document.getElementById('match-list');
*/

class handleSQLite {
    constructor() {
        this.db;
    }


    openDatabase() {
        this.db = new sqlite3.Database('./db/storage.db', (err) => {
            if (err) {
                console.error(err.message);
            } else {
                console.log('Connected to the in memory SQlite database.')
            }
        });
    }

    closeDatabase() {
        this.db.close((err) => {
            if (err) {
              console.error(err.message);
            }
            console.log('Close the database connection.');
          });
    }
    
}

/*
const data = new handleSQLite();

data.openDatabase();

data.closeDatabase();
*/








/*
let db = new sqlite3.Database('./db/storage.db', (err) => {
    if (err) {
        console.error(err.message);
    } else {
        console.log('Connected to the in memory SQlite database.')
    }
});
*/

let sqlItemSearchSuggest = `SELECT ItemName itemName
                            FROM   storage`

let sqlCreate = `CREATE TABLE storage(BoxNum REAL, ItemName TEXT, Location TEXT)`

let sqlInsert = "INSERT INTO storage VALUES(1, 'waffle maker', 'Storage Room')"


const searchSearchItems = async searchText => {
    const searchRes = await database.db.each(`SELECT ItemName FROM storage`, (err, row) => {
        if (err) {
            throw err;
        }
    }).toArray();
    

    console.log(searchItems);

    let searchMatches = searchRes.filter(searchItem => {
        console.log(searchItem);
        const searchRegex = new RegExp(`^${searchText}`, 'gi');
        return searchItem.itemName.match(searchRegex);
    });
    if (searchText.length === 0) {
        searchMatches = [];
        searchMatchList.innerHTML = '';
    }
    
    outputSearchHtml(searchMatches);
};


const outputSearchHtml = searchMatches => {
    if (searchMatches.length > 0) {
        const html = searchMatches.map(searchMatch => `
        <div class ="card">
            <h4>${searchMatch.name}</h4>
        </div>
        `).join('');

        searchMatchList.innerHTML = html;
    }
}

module.exports = handleSQLite;

It is just very frustrating as I know how I want to do everything else but just cannot get past this hurdle.

Oh then I guess here is my index.html as well

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css"/>



    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Comic+Neue&display=swap" rel="stylesheet">


    <title>Storage Lookup</title>
</head>
    <body>
        <div class="btns">
            <button class="sel-btn search">Search</button>
            <button class="sel-btn insert">Insert</button>
            <button class="sel-btn remove ">Remove</button>
        </div>

        <div class="search-sec hidden">
            <p>by</p>
            <div class="search-btns">
                <button class="search-sec-btn">Box</button>
                <button class="search-sec-btn">Item</button>
            </div>
            <div class="search-input-go">
                <div class="search-input-cont">
                    <input type="text" id="search-input" placeholder="Item Name">
                    <input type="image" src="/img/search.png" name='searchbtn' class="search-btn"/>
                </div>
                <div id="match-list"></div>
            </div>
        </div>

        <div class="insert-sec hidden">

            <div class="insert-btns">
                <input type="text" class="insert-input" id='input-insert-box' placeholder="Box Number">
                <input type="text" class="insert-input" id='insert-input-item' placeholder="Item Name">
            </div>
            <div class="insert-btn-con">
                <button class="insert-sec-btn">Insert</button>
            </div>
        </div>

        
        <script type="module" src="main.js"></script>
        
    </body>
</html>

Solution

  • The difference

    If I understood you correctly, what you are trying to do is impossible. You can't access db from browser directly.

    Unless nodejs and browser-side javascript "speaking" one language, they are very different things. NodeJS is designed to be server-side, so it uses server specific things like Operating system related utils, filesystem.

    So running sqlite in browser is like running jquery on server -- there is no such a thing like DOM in NodeJS like there is no such a thing like fs in browser.

    How then?

    In the common case the client code and the server code don't know much about each other. They deal with each other via API like classical client-server apps.

    Simple example abstractly looks like:

    Browser: asks server for /api/users route via GET request Server: does the job like going to DB, extracts data Server: return data to Browser, mostly likely in JSON Browser displays data

    and etc.