user4909217
user4909217

Reputation:

Cannot run node file in the index page

I am new in computer science and i love programming. So I start learning nodejs and i have wrote this simple code in test.js..

var http = require("http");
var fs=require('fs');
var path=require('path');
var msg= "hi\nhow r u ?\nfine";
var file='textms.txt';
http.createServer(function (req,res){
    fs.open(file,function(exists){
        if(exists){
            fs.open(file,msg,function(err){
                if(err)throw err;   
            });
        }else{
            fs.writeFile('test.txt',msg);
            console.log('New file is created : ');
        }

    });
    res.end();
}).listen(8080);

console.log('server running on port 8080');

this is my index.html page code ..

<html>
    <head>
        <title>
            Chat Test With Nodejs
        </title>
    <script type="text/javascript" src="test.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
    <body>
    <div id="cnt"></div>
    <input type="text" class="text">
    <button id="btn">Send</button>
    </body>
</html>

i run this code on chrome(localhost:8080). it works fine.

Problem: when i run my index.html page on chrome, i get this error in chrome console:

Uncaught ReferenceError: require is not defined @ server.js:1

i tried to search on google, i didnt find anything useful. Questions: why i am getting this error ?

Upvotes: 2

Views: 610

Answers (3)

User 1058612
User 1058612

Reputation: 3819

Is server.js the in your HTML file pointing to your Node server? If so, then your browser is trying to run a Node server (or node file) which it can't do. Also, your error seems to be that require is not defined, which makes perfect sense, because require is a Node function, not a native JS function.

Upvotes: 1

num8er
num8er

Reputation: 19372

Dumb! :)

NodeJS is serverside javascript interpreter.
So You cannot include it in Your html code.
1. install nodejs
2. navigate to folder where server.js lies
3. and run from command prompt:

node server.js

or

nodejs server.js

and then open in Your browser: http://127.0.0.1:8080

p.s. go watch tutorials in Youtube: https://www.youtube.com/watch?v=-u-j7uqU7sI&index=1&list=PL6gx4Cwl9DGBMdkKFn3HasZnnAqVjzHn_

Upvotes: 1

Max Baldwin
Max Baldwin

Reputation: 3472

Looks like you are pretty new to Node. To answer your question, you don't run your server file in your index.html. Your server file is what runs your index.html.... Kinda.

Rather than going on a really long explanation about how Node works, I am going to give you this resource, NodeSchool. Probably one of the best places to start learning Node.

Good luck and if you every have any questions, feel free to reach out.

Thanks,

Upvotes: 1

Related Questions