ace编辑器无法在socket.io节点应用程序中工作

时间:2019-01-07 05:04:44

标签: node.js socket.io ace-editor

在我的Socket应用中,我试图将编程代码作为消息发送给另一个客户端。如果仅运行HTML,它将完美显示Ace编辑器。但是当我运行node app.js时,ace编辑器不起作用,我已经下载了ace-builds并在应用中安装了npm ace-code-editor,但没有任何变化
这是我的代码     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>

需要解决方案

1 个答案:

答案 0 :(得分:0)

您正在呼叫window.ace.edit("m");,直到该元素可用。 将脚本标签移到文件末尾,或将ace初始化移到$ call中。