1.0.0 • Published 2 years ago
localhost-app v1.0.0
Localhost-App
Creates a localhost server using express and ws (for backend support). We recommend using open to open the app.
Install
npm install localhost-app
Usage
Server-side (e.g. index.js)
//SERVER-SIDE (index.js)
const app = require("localhost-app")
app.setServerRoot("resources")
app.setStartPage("mainWindow")
//sets start page to <project>/resources/mainWindow/index.html
app.init(function(url) {
console.log(`App running: ${url}`) //e.g. App running: http://localhost:1234
app.setBackend({
ping(res) {
res("pong")
}
})
})
API Documentation
app.setServerRoot(path: string) -> void
Sets the directory to serve.
app.setStartPage(path: string) -> void
Redirects root to the specified path. Example:
app.setServerRoot("dirA")
app.setStartPage("dirB")
//structure
project
|-index.js
| |-dirA
| | |-dirB
| | | |-index.html// <-- this file will be opened
app.init(cb: (url) => void) -> void
Initiates the server and triggers the callback function.
app.init(function(url) {
console.log(url) //e.g. http://localhost:1234
})
app.backend(functions: {}) -> void
Defines backend functions. The res() function is used to reply.
app.backend({
sum(res, n1, n2) {
res(n1 + n2)
}
})
Client-side (window)
const ws = new WebSocket(`ws://${window.location.host}`)
ws.onopen = function() {
ws.send(JSON.stringify(
["sum", 1, 2]
))
ws.onmessage = function(message) {
const data = message.data
//data == '["sum", 3]'
if (data[0] == "sum") {
console.log(data[1]) //3
}
}
}