Skip to content

Instantly share code, notes, and snippets.

@PsychoLlama
Created August 25, 2016 20:48
Show Gist options
  • Save PsychoLlama/f30b2dac2b3b624fd5a6bf98e7d0c442 to your computer and use it in GitHub Desktop.
Save PsychoLlama/f30b2dac2b3b624fd5a6bf98e7d0c442 to your computer and use it in GitHub Desktop.
Using gun-level with SQLite3 on Windows
'use strict';
/*
Really this is the server.js file, but due to
gist limitations, the first filename has to
be the description.
*/
const Gun = require('gun-level');
// Required for side-effects, adds `.wsp()`.
require('gun');
const Server = require('http').Server;
const path = require('path');
const fs = require('fs');
const levelup = require('levelup');
const sqldown = require('sqldown');
// Creates a new level instance using sqlite3.
// Before doing this, you need `sqlite3` installed via npm.
const level = levelup('data.sqlite', {
db: sqldown,
});
const gun = new Gun({
// This is sent to gun-level.
level: level,
// This disables gun's "file.js" module (data.json).
file: false,
});
// Listen for /gun.js requests.
const server = new Server(gun.wsp.server);
// Attaches a websocket handler on the "/gun" route.
gun.wsp(server);
// Starts the server.
server.listen(8080);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gun-Level chat app</title>
</head>
<body>
<ul></ul>
<form>
<input type="text" placeholder="Message">
<button type='submit'>Send</button>
</form>
<!-- Loads gun through our `gun.wsp.server()` handler. -->
<script src='http://localhost:8080/gun.js'></script>
<script>
const gun = new Gun('http://localhost:8080/gun');
// Get some UI elements.
const ul = document.querySelector('ul');
const form = document.querySelector('form');
const input = document.querySelector('input');
const messages = gun.get('messages');
// For each message...
messages.map().val(function (message) {
// Create a list item and add it to the chat <ul>.
const li = document.createElement('li');
li.innerText = message.body;
ul.appendChild(li);
});
form.addEventListener('submit', function (event) {
// Prevent the form from reloading the page.
event.preventDefault();
event.stopPropagation();
// Get the new message and clear out the value.
const body = input.value;
input.value = '';
// Create a new gun message node and add it to the messages list.
const message = gun.put({ body: body });
messages.set(message);
});
</script>
</body>
</html>
{
"name": "windows-gun-level-chat",
"version": "1.2.3",
"description": "Gun-Level chat app, windows-compatible",
"main": "gun-level-windows.js",
"scripts": {
"start": "node gun-level-windows.js"
},
"author": "",
"license": "MIT",
"dependencies": {
"gun": "^0.3.992",
"gun-level": "^4.0.0",
"levelup": "^1.3.2",
"sqldown": "^2.1.0",
"sqlite3": "^3.1.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment