I am html javascript beginner and i simply have to read the contents of a text file at a location and store each column in that file in an array (there are 3 columns) in html and i use javascript to do so.
I have came across 2 errors http://prntscr.com/6ilvhx :
(1)ReferenceError: require is not defined
(2) ReferenceError: readfile is not defined
My code to do this is :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
console.log("just a check1");
var fs = require('fs');
console.log("just a check2");
function readLines(input, done) {
var arr = [];
var remaining = '';
input.on('data', function (data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function () {
if (remaining.length > 0) {
func(remaining);
done(arr);
}
});
function func(data) {
arr.push(data.split(/\s+/g));
}
}
var input = fs.createReadStream('Content\TextFile\distinctGimeiNo.txt');
readLines(input, done);
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
var key3 = arr[0][3];
obj[key1] = [];
obj[key2] = [];
obj[key3] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
obj[key3].push(item[2]);
});
console.log('X:', obj['X']);
console.log('Y:', obj['Y'])
console.log('Z:', obj['Z'])
}
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
How to make it work ?I found this on debugging http://prntscr.com/6ilvhx
Updated code : (after adding library)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src=http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js>
console.log("just a check1");
var fs = require('fs');
console.log("just a check2");
function readlines(input, done) {
var arr = [];
var remaining = '';
input.on('data', function (data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index >
-1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function () {
if (remaining.length > 0) {
func(remaining);
done(arr);
}
});
function func(data) {
arr.push(data.split(/\s+/g));
}
}
var input = fs.createReadStream('Content\TextFile\distinctGimeiNo.txt');
readLines(input, done);
function done(arr) {
var obj = {};
var key1 = arr[0][0];
var key2 = arr[0][1];
var key3 = arr[0][2];
obj[key1] = [];
obj[key2] = [];
obj[key3] = [];
arr.shift();
arr.forEach(function (item) {
obj[key1].push(item[0]);
obj[key2].push(item[1]);
obj[key3].push(item[2]);
});
console.log('X:', obj['X']);
console.log('Y:', obj['Y'])
console.log('Z:', obj['Z'])
}
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>