var express = require("express")
var app = express()
var bodyParser = require("body-parser")
var fs = require('fs')
app.use(bodyParser.json())
app.get('/file/:name', function (request, response) {
var content = ''
if (fs.existsSync(request.params.name)) {
content = fs.readFileSync('./' + request.params.name)
} else {
fs.appendFileSync('./' + request.params.name, request.params.name)
content = fs.readFileSync('./' + request.params.name)
}
response.send(content)
})
app.post('/file/:name', function (request, response) {
console.log(request.body)
fs.writeFileSync('./' + request.params.name, request.body.content)
response.send(fs.readFileSync('./' + request.params.name))
})
app.get('/', function (request, response) {
response.send(`<html>
<head>
<meta charset="UTF-8">
<title>Task39</title>
<script>
window.addEventListener('load', function() {
console.log('loaded')
var list = document.getElementById('list')
list.addEventListener('change', function(e) {
loadFile(e.target.options[e.target.options.selectedIndex].innerText)
})
loadFile(list.options[list.options.selectedIndex].innerText)
})
loadFile = (filename) => {
fetch('/file/' + filename).then(r => r.text()).then(r => document.getElementById('file').value = r)
}
save = () => {
var list = document.getElementById('list')
fetch('./file/' + list.options[list.options.selectedIndex].innerText,
{
method: 'post',
body: JSON.stringify({ content: document.getElementById('file').value }),
headers: new Headers({'content-type': 'application/json'}),
}
)
}
</script>
</head>
<body>
<select id="list">
<option>a.html</option>
<option>b.html</option>
</select>
<br>
<textarea id="file" style="width: 20%; height: 200px"></textarea>
<br>
<button onclick="save()">Save</button>
</body>
</html>
`)
})
app.listen(2999, function () {
console.log("Started on PORT 2999");
})
) схематично,...