Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 7403

Browserify with nodejs is not working

I am creating a sample application to learn how to use nodejs for client side. I have installed : node, npm with browserify before running this exercise;

Directory Structure

lesseon1
 - index.html
 - application.js
 - js
   - data.js
   - listdata.js

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Node Lesson 1</title>
    <script type="text/javascript" src="application.js"></script>
</head>
<body>
<div id="names"></div>
    <script type="text/javascript">
        var ol = document.createElement("ol");
        ol.innerHTML = window.list;
        document.getElementById("names").appendChild(ol);
    </script>
</body>
</html>

listdata.js

var jsonData = require("./data.js");

for(item in jsonData){
    console.log(jsonData[item].name);
    window.list += "<li>" + jsonData[item].name + "</li>";
}

console.log(window.list);

data.js

var json = [{
    "name" : "Rohit"
    },{
    "name" : "Amit"
    },{
    "name" : "Arti"
    }];

And application.js is being generated using browerify

~/node_modules/.bin/browserify -e js/listdata.js -o application.js

Problem :

It is printing undefined in browser and browser console too. However if I copy paste js code in index.html, everything works fine. In listdata.js, there are 2 console.log() statements. But it is executing only last one.

Am I missing something? or doing something in wrong way.

Upvotes: 0

Views: 458

Answers (1)

edin-m
edin-m

Reputation: 3121

You did not export from data.js.

var json = [{
    "name" : "Rohit"
    },{
    "name" : "Amit"
    },{
    "name" : "Arti"
    }];
module.exports = json;

Or you can change to data.json and just type in valid json without var or exports and use it in listdata.js as var jsonData = require("./data.json");

Each required file, browserify wraps into function with function (require, module, exports) signature. That is reason why you might not have some variables globally. If you want so, use global. or window..

Upvotes: 1

Related Questions