Search code examples
javascriptserverside-javascript

JavaScript as a server-side language


i have been trying to understand how JavaScript can function as server-side language as i am used to JavaScript for client-side work such as AJAX. can someone explain to me succinctly, i have Java and OOP experience and can't wrap my head around the fact that since JS is stateless.

Much thanks, if answers are really in-depth and profound i will make this into a community wiki. I know nodeJS accomplishes server-side coding using JS, but is it because it is compiled using Google V8 engine?

On the other hand, in AJAX, JS is used as logic on the page..


Solution

  • What do you mean javascript is stateless? Here's a simple node.js server with transient state (lost on a server reboot):

    var http = require('http');
    
    var someState = 0;
    
    http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Javascript has state: ' + someState++ + '\n');
    }).listen(1337, '127.0.0.1');
    console.log('Server running at http://127.0.0.1:1337/');
    

    I know nodeJS accomplishes server-side coding using JS, but is it because it is compiled using Google V8 engine?

    That's like asking "I know you can do server-side coding with PHP, but is it because it requires a PHP runtime?"