Javascript inherited object overwrites other inherited object - javascript

Can someone please explain what the correct way is to have multiple objects inherit from a parent and have their own prototype functions? I'm trying to do this in nodeJS.
I have these files.
ParserA_file
var ParentParser = require('ParentParser_file');
module.exports = ParserA;
ParserA.prototype = Object.create(ParentParser.prototype);
ParserA.prototype.constructor = ParserA;
ParserA.prototype = ParentParser.prototype;
function ParserA(controller, file) {
ParentParser.call(this, controller, file);
this.controller.log('init --- INIT \'parser_A\' parser');
this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/;
this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/;
this.date_format = 'DDMMMYY HH:mm';
}
ParserA.prototype.startParse = function() {
console.log('Starting parse for A');
}
ParserB_file
var ParentParser = require('ParentParser_file');
module.exports = ParserB;
ParserB.prototype = Object.create(ParentParser.prototype);
ParserB.prototype.constructor = ParserB;
ParserB.prototype = ParentParser.prototype;
function ParserB(controller, file) {
ParentParser.call(this, controller, file);
this.controller.log('init --- INIT \'parser_B\' parser');
this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/;
this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/;
this.date_format = 'DDMMMYY HH:mm';
}
ParserB.prototype.startParse = function() {
console.log('Starting parse for B');
}
ParentParser_file
ParentParser = function(controller, file) {
if (!controller) {
throw (new Error('Tried to create a Parser without a controller. Failing now'));
return;
}
if (!file ) {
throw (new Error('Tried to create a Parser without a file. Failing now'));
return;
}
this.controller = null;
this.file = null;
}
module.exports = ParentParser;
Now I require them both in my node app
var ParserA = require('ParserA_file');
var ParserB = require('ParserB_file');
Now, when only one parser is loaded the there is no problem, however, loading them both into my node app and starting parser A
var parser = new ParserA(this, file);
parser.startParse()
returns
init --- INIT 'parser_B' parser'
Now for the question, how come ParserB's function startParse overwrites the startParse from ParserA?

That's because they refer to the same prototype object.
ParserA.prototype = ParentParser.prototype;
...
ParserB.prototype = ParentParser.prototype;
ParserA.prototype === ParserB.prototype; // true
Remove those two lines (which are overwriting the two lines above them anyway) and you'll be good to go.

Related

Browserify require - inline way. How?

Is there any possibility to include one file into another with Browserify?
I mean not standard Browserify behavior, but pasting one file into another in a specific place.
file1.js
console.log("abc");
file2.js
requirePaste("file1.js");
console.log("def");
output.js
console.log("abc");
console.log("def");
I need it for spreading an ES6 class into multiple files like this pattern:
ObjectManager.js
ObjectManager_Events.js
ObjectManager_Rendering.js
These files are about one class. So I can make something like this:
class ObjectManager {
constructor() {
}
requirePaste("./ObjectManager_Events");
requirePaste("./ObjectManager_Rendering");
}
EDIT:
I made a simple transform plugin for Browserify and it works great. There is one problem though it won't work with Watchify. this is because inline-required files aren't counted as being watched. Any idea on how to fix this?
const through = require('through2');
const fs = require('fs');
const path = require('path');
const regex = /require\([\s]*\/\*inline\*\/[\s]*"(.+)"\)/g;
function process(pathToFile, contents) {
while ( (occurence = regex.exec(contents)) ) {
contents = processOne(pathToFile, contents, occurence);
}
return contents;
}
function processOne(pathToFile, contents, occurence) {
const dir = path.dirname(pathToFile);
const includePath = occurence[1] + ".js";
const range = [occurence.index, occurence.index+occurence[0].length-1];
const pathToInnerFile = dir + "/" + includePath;
var innerContents = fs.readFileSync(pathToInnerFile, 'utf8');
innerContents = process(pathToInnerFile, innerContents);
var output = "";
output += contents.substring(0, range[0]);
output += innerContents;
output += contents.substring(range[1]+1);
return output;
}
module.exports = function(pathToFile) {
return through(
function(buf, enc, next) {
var result = process(pathToFile, buf.toString('utf8'));
this.push(result);
next();
}
);
};
That did the trick:
Basically we inform Watchify about file by emiting 'file' event.
const includedFiles = [];
function process(pathToFile, contents) {
includedFiles.push(pathToFile);
while ( (occurence = regex.exec(contents)) ) {
contents = processOne(pathToFile, contents, occurence);
}
return contents;
}
...
module.exports = function(pathToFile) {
return through(
function(buf, enc, next) {
var result = process(pathToFile, buf.toString('utf8'));
this.push(result);
includedFiles.forEach((filePath) => this.emit("file", filePath));
includedFiles.length = 0;
next();
}
);
};

Getting database information from other file

I have 3 different files called: app.js, ServerManager.js and Users.js.
To start everything, I run app.js which runs my ServerManager.
Running ServerManager in App.js:
var ServerManager = require('./modules/ServerManager.js');
var serverManager = new ServerManager({
app: app,
path: __dirname
});
Then serverManager is called and I can do stuff in there, then I'm trying to send stuff to Users.js from ServerManager but it seems like it doesn't work.
ServerManager.js
var config = require('../config.js');
var express = require('express');
var colors = require('colors');
var DatabaseManager = require('../modules/DatabaseManager.js');
var RouteManager = require('../modules/RouteManager.js');
var Users = require('../data/users.js');
module.exports = function(options){
return new ServerManager(options);
}
var ServerManager = function (options) {
var self = this;
this.app = options.app;
this.options = options;
this.dbManager = new DatabaseManager();
this.dbManager.use();
this.RoutesManager = new RouteManager(this.app);
this.RoutesManager.use();
this.usersManager = new Users(this);
}
ServerManager.prototype.getDatabase = function () {
return this.dbManager();
}
Users.js - Marked in code what it can't find.
module.exports = function (ServerManager) {
return new Users(ServerManager);
};
var Users = function (ServerManager) {
var self = this;
this.serverManager = ServerManager;
};
Users.prototype.createUser = function (username, email, password) {
this.serverManager.getDatabase(); <--- Can't find getDatabase()
};
I think that you should change your Users.js code to:
// This is the Users object
// and this function is its constructor
// that can create users instances
var Users = function (ServerManager) {
var self = this; this.serverManager = ServerManager;
};
// We define a method for the user object
Users.prototype.createUser = function (username, email, password) {
this.serverManager.getDatabase();
};
// We export the user object
module.exports = Users;
Now the then you do
var Users = require('../data/users.js');
you get the User object.
And so, you can do new Users(...).
The same thing has to be done for the ServerManager.
If you want to use your code as it is, you don't have to use the new keyword on the imported object.

Node JS - How to write stream big json data into json array file?

I have difficult to write a json data into json file using stream module.
I learn about this from several blog tutorial, one of them is this page
Let say i am working with big json data on a json file. I think it is not possible to store all json object inside my memory. So i decided to do it using stream module.
Here the codes i have done:
writeStream.js
var Writable = require('stream').Writable,
util = require('util');
var WriteStream = function() {
Writable.call(this, {
objectMode: true
});
};
util.inherits(WriteStream, Writable);
WriteStream.prototype._write = function(chunk, encoding, callback) {
console.log('write : ' + JSON.stringify(chunk));
callback();
};
module.exports = WriteStream;
readStream.js
var data = require('./test_data.json'),
Readable = require('stream').Readable,
util = require('util');
var ReadStream = function() {
Readable.call(this, {
objectMode: true
});
this.data = data;
this.curIndex = 0;
};
util.inherits(ReadStream, Readable);
ReadStream.prototype._read = function() {
if (this.curIndex === this.data.length) {
return this.push(null);
}
var data = this.data[this.curIndex++];
console.log('read : ' + JSON.stringify(data));
this.push(data);
};
module.exports = ReadStream;
Called with this code:
var ReadStream = require('./readStream.js'),
WriteStream = require('./writeStream.js');
var rs = new ReadStream();
var ws = new WriteStream();
rs.pipe(ws);
Problem: I want to write it into different file, how is it possible?
Can you please help me?
If you are looking for a solution to just write the data from your ReadStream into a different file, you can try fs.createWriteStream. It will return you a writeable stream which can be piped directly to your ReadStream.
You will have to make a minor change in your readStream.js. You are currently pushing an object thus making it an object stream while a write stream expects either String or Buffer unless started in the ObjectMode. So you can do one of the following:
Start the write stream in the object mode. More info here.
Push String or Buffer in your read stream as writable stream internally calls writable.write which expects either String or Buffer. More info here.
If we follow the second option as an example, then your readStream.js should look like this:
var data = require('./test_data.json'),
Readable = require('stream').Readable,
util = require('util');
var ReadStream = function() {
Readable.call(this, {
objectMode: true
});
this.data = data;
this.curIndex = 0;
};
util.inherits(ReadStream, Readable);
ReadStream.prototype._read = function() {
if (this.curIndex === this.data.length) {
return this.push(null);
}
var data = this.data[this.curIndex++];
console.log('read : ' + JSON.stringify(data));
this.push(JSON.stringify(data));
};
module.exports = ReadStream;
You can call the above by using the following code
var ReadStream = require('./readStream.js');
const fs = require('fs');
var rs = new ReadStream();
const file = fs.createWriteStream('/path/to/output/file');
rs.pipe(file);
This will write the data from test_data.json to the output file.
Also as a good practice and to reliably detect write errors, add a listener for the 'error' event. For the above code, you can add the following:
file.on('error',function(err){
console.log("err:", err);
});
Hope this helps.

mocha import external script failed

I have this opcode.js file and need to test it with mocha.An example can be seen here :
var opcode = {
'0': {
decode: function (data) {
var ocBuf = new OpcodeBuffer(data);
var kpo = {};
kpo.opcode = 0x00;
ocBuf.setIndex(1);
kpo.sid = ocBuf.readUInt16();
return kpo;
},
encode: function (kpo) {
var ocBuf = new OpcodeBuffer(opcode['0'].encodeLength(kpo));
ocBuf.writeUInt8(0x00);
ocBuf.writeUInt16(kpo.sid);
return ocBuf.buf;
}
module.exports = opcode;
and the write in my test_ack.js file:
var op = require('./ack.js');
var assert = require('assert');
opcode = op.opcode;
var decode = require('opcode').decode();
var encode = require('opcode').encode();
the problem is that i keep having this encode and decode not defined error messages.I still cannot get how can i import them in my directory.
Given the code you show us, this would be the way you could import your two functions:
var decode = require('opcode')["0"].decode;
var encode = require('opcode')["0"].encode;
I'd suggest additionally avoiding calling require twice. Among other things, the code you currently have calls the functions instead of just importing them.

How can I use these Node modules to accept HTML through a file or URL and then output JSON as validation of existing HTML elements?

Essentially what I need to do is to take a local grader.js file and then use it at the command line to input HTML, which will then output JSON data to the console to validate the existence of several HTML elements. The usage looks something like this:
./grader.js --checks checks.json --file index.html
./grader.js --checks checks.json --url http://google.com
The Node modules being used are Commander (for working at the command line), Cheerio (for HTML), and Restler (for getting HTML from URL).
The checks.json file is straightforward in that it's simply asking to check for the existence of a few simple HTML elements to find out whether or not they exist on the page:
["h1",
".navigation",
".logo",
".blank",
".about",
".heading",
".subheading",
".pitch",
".video",
".thermometer",
".order",
".social",
".section1",
".section2",
".faq",
".footer"]
The grader.js file is where things get a little more complicated. The following code actually works insofar as it takes the command line arguments and does indicate a true or false value as to whether the HTML elements exist. But it doesn't work properly after adding the URL check at the bottom. There is something wrong with my checkURL function and the way that I implement it using the Commander code at the bottom. Even though the true and false values are correct dependent upon the HTML file/URL I use, I end up spitting out both checks to the console even if I only want to check either the file or the URL, not both. I'm fairly new to this so I'm surprised that it works at all. It may have something to do with the default values, but when I try to make those changes the checkURL function seems to break down. Thanks in advance for your help I really do appreciate it.
#!/usr/bin/env node
var fs = require('fs');
var program = require('commander');
var cheerio = require('cheerio');
var rest = require('restler');
var HTMLFILE_DEFAULT = "index.html";
var CHECKSFILE_DEFAULT = "checks.json";
var URL_DEFAULT = "http://cryptic-spire-7925.herokuapp.com/index.html";
var assertFileExists = function(infile) {
var instr = infile.toString();
if(!fs.existsSync(instr)) {
console.log("%s does not exist. Exiting.", instr);
process.exit(1); // http://nodejs.org/api/process.html#process_process_exit_code
}
return instr;
};
var cheerioHtmlFile = function(htmlfile) {
return cheerio.load(fs.readFileSync(htmlfile));
};
var loadChecks = function(checksfile) {
return JSON.parse(fs.readFileSync(checksfile));
};
var checkHtmlFile = function(htmlfile, checksfile) {
$ = cheerioHtmlFile(htmlfile);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
return out;
};
var checkUrl = function(url, checksfile) {
rest.get(url).on('complete', function(data) {
$ = cheerio.load(data);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
console.log(out);
});
}
var clone = function(fn) {
// Workaround for commander.js issue.
// http://stackoverflow.com/a/6772648
return fn.bind({});
};
if(require.main == module) {
program
.option('-f, --file <html_file>', 'Path to index.html', clone(assertFileExists), HTMLFILE_DEFAULT)
.option('-u, --url <url>', 'URL to index.html', URL_DEFAULT)
.option('-c, --checks <check_file>', 'Path to checks.json', clone(assertFileExists), CHECKSFILE_DEFAULT)
.parse(process.argv);
var checkJson = checkHtmlFile(program.file, program.checks);
var outJson = JSON.stringify(checkJson, null, 4);
console.log(outJson);
var checkJson2 = checkUrl(program.url, program.checks);
var outJson2 = JSON.stringify(checkJson2, null, 4);
console.log(outJson2);
}
else {
exports.checkHtmlFile = checkHtmlFile;
}
Depending on the arguments call either one of checkHtmlFile() or checkUrl()
Something like:
if (program.url)
checkUrl(program.url, program.checks);
else checkHtmlFile(program.file, program.checks);
Read this for more references: commander.js option parsing
Also, checkJson2 is undefined as checkUrl() isn't returning anything.
Those commander .option lines look wrong to me.
Delete the clone function and revise your option lines as follows:
.option('-f, --file <html_file>', 'Path to index.html', HTMLFILE_DEFAULT)
.option('-u, --url <url>', 'URL to index.html', URL_DEFAULT)
.option('-c, --checks <check_file>', 'Path to checks.json', CHECKSFILE_DEFAULT)
This should solve your commander problem.
Here is the updated checkUrl function after the helpful hints from #David and #ankitsabharwal.
var checkUrl = function(url, checksfile) {
rest.get(url).on('complete', function(data) {
$ = cheerio.load(data);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
var outJson = JSON.stringify(out, null, 4);
console.log(outJson);
});
}
And here is the updated Commander code below:
if(require.main == module) {
program
.option('-f, --file <html_file>', 'Path to index.html')
.option('-u, --url <url>', 'URL to index.html')
.option('-c, --checks <check_file>', 'Path to checks.json')
.parse(process.argv);
if (program.url) {
checkUrl(program.url, program.checks);
} else {
checkHtmlFile (program.file, program.checks);
var checkJson = checkHtmlFile(program.file, program.checks);
var outJson = JSON.stringify(checkJson, null, 4);
console.log(outJson);
}
}

Categories