In my Socket app, I'm trying to send programming code as a message to another client. If run the HTML only it shows the Ace editor perfectly. But when I run node app.js the ace editor doesn't work.I have downloaded ace-builds and installed npm ace-code-editor in the app, but nothing changes
here is my code
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
})
socket.on('chat message', function (msg) {
console.log("message: " + msg);
io.emit('chat message', msg);
});
});
http.listen(port, function () {
console.log('listening on *:' + port);
});
index.html
<html>
<head>
<title>Socket.IO </title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#m {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var editor = window.ace.edit("m");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/javascript");
$(function () {
var socket = io();
var myvar = setInterval(task, 100)
function task() {
var code=editor.getValue();
socket.emit('chat message',code);
}
socket.on('chat message', function (msg) {
editor.setValue("the new text here");
});
});
</script>
</head>
<body>
<div id="m">function foo(items) {
var x = "All this is syntax highlighted";
return x;
} </div>
</body>
</html>
Need a solution
you are calling window.ace.edit("m");
before that element becomes available.
Move script tag to the end of the file, or move ace initialization into $ call.