Error during synchronous write using Node.js - javascript

I have written code that parses a dictionary returned from Firebase containing images encoded using base64. I want it to simply write these images to file, and it does, but I receive the following error after my writes finish:
smalloc.cc:280: void node::smalloc::SliceOnto(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `end <= source_len' failed.
This is my code:
// Iterate through each key in each page if each request
for (var key in request) {
var obj = request[key];
if (typeof (obj) == "object") {
for (var prop in obj) {
item++;
if(obj.hasOwnProperty(prop)) {
switch (prop) {
case "img":
var media = new ReceivedMedia(obj[prop]);
var filename = transaction.tid + "-" + item + "." + media.extension;
filename = filename.slice(10);
require('fs').writeFileSync(filename, media.b64, 'base64', function(err) {
if (err) throw err;
});
break;
}
}
}
}
}
My images come out fine, but the error is a little weird and I would prefer to not to occur. Would anyone have an idea as to why this is happening? That would be super helpful :)
Note: ReceivedMedia is a class I defined as:
function ReceivedMedia(media) {
this.b64 = media.b64;
this.extension = media.extension;
this.posx = media.posx;
this.posy = media.posy;
}
Side question: If I use writeFile instead of writeFileSync one of my images is corrupted and the other contains no data. If after that happens I run my node script again, the files save correctly. I would also like some explanation as to why that happens, from my understanding one of these is synchronous (writeFileSync I am guessing) and the other is asynchronous (writeFile I am assuming).

A Google search for your error message description found this discussion of the issue in io.js and this discussion in node.js and it sounds like it is a bug that has been fixed (not sure if the fix has been released in a full build yet).
The node.js fix is here.
If you were desparate to fix it now in your own build, you'd have to apply the fix to your own code tree and rebuild it. Otherwise, you'll have to investigate or inquire when this fix will get into an official release (I'm not personally sure how that process works for node.js).

Related

How to properly import a javascript file/function API to a React.js app?

Hey Stackoverflow :) Long time reader, first time poster. To the point:
I'm fairly new to web programming (done much more C# and game programming). I've been given a task that requires me to write a simple React.js app. I am to use an included api.min.js javascript file that includes an "API", that is supposed to sort of mimic a server, has a set of built in functions to fetch data ('/getitem', '/getusers', '/putitem', etc), and mimics lost requests now and then. The API code has been minified and is one single line of some 4500 characters, and sadly i don't think i can include all the code from this file, since it's not mine (and, well it's 4500 chars :P). But some clues: when beautified it starts off like this:
var api = function() {
function t(t) {
for (var e = t.length - 1; e > 0; e--) {
var n = Math.floor(Math.random() * (e + 1)),
r = t[e];
t[e] = t[n], t[n] = r
}
return t
etc...
And ends like this:
etc...
},
setRequestHeaders: function(t, e) {
if ("number" != typeof t && "string" != typeof t && "number" != typeof e && "string" != typeof e) throw new Error("Arguments both header and value must be numbers or strings");
l[t] = e
}
};
return m
};
return {
XMLHttpRequest: y
}
}();
One of the examples included in the file looks like this:
// Example 1:
var x = api.XMLHttpRequest();
x.onreadystatechange = function() {
console.log(x.readyState, x.status, x.responseText);
};
x.open("GET", "/getusers");
x.send();
If i paste the API line and the example code into say, jsfiddle.net, it works fine and gives me the data in a format i would know how to use. But i can't seem to get it to work in my React-project in VScode. Whenever i try to import the file, i get errors of the type
Line 6:7: Expected an assignment or function call and instead saw an expression no-unused-expressions
That would be the line:
t[e] = t[n], t[n] = r
... from the first code example above.
So I'm a bit clueless as to how to proceed atm... Does anyone have any suggestions on how i could include this API in my VScode React.js project and access the functions from the api.min.js file? I feel like there probably is some really simple solution to this, but as i said, i am fairly new to web programming and i still lack some of the fundamentals i think. I've looked around here, google, youtube etc but i can't seem to find what I'm looking for. Might be because i don't really know what i'm looking for :)
If anyone could help i would be ever grateful!
Thanks

Can anyone explain how to work with conversationThreading-js?

I am trying to use this conversationThreading-js code to group emails into threads but documentation is scant and/or I am not able to understand it. Has anyone used this bit of code before or used the JWZ email conversation threading algorithm on which it is based?
This is where I am so far:
using Electron I load and parse a local mbox using node-mbox and node-mailparser
I build an array of javascript objects which have key value pairs of messageId, inReplyTo and references.
Using example code from the test file for this lib I try to build the threads but apparently I am not doing it right. I get no errors but I also get no threads (and my test mbox does contain threaded conversations).
Maybe I am misunderstanding what the result should be? Or I am just "doing it wrong"? My end goal here is to be able to display the resulting threads in some sort of directed graph using D3 – but that is not going to happen if I can't get the data set up correctly.
function makeThread(emails) {
var thread = jwz.messageThread().thread(emails.map(
function (message) {
return jwz.message(message.subject, message.messageId, message.references);
}
));
console.log('thread',thread);
}
It's pretty unclear how it works, but I managed to write some code that prints the "thread tree":
function recurse(node, level) {
level = level || 0;
let prefix = '\t'.repeat(level);
(node.children || []).forEach(function(child) {
child.children = child.children || [];
console.log(prefix, level ? '' : '-', child.message ? child.message.subject : '??', `[${ child.children.length }]`);
return recurse(child, level + 1);
});
}
recurse(jwz.messageThread().thread(messages));
(messages is an array of jwz.message() objects, similar to how you're creating it)

How can I trigger an error from inside gulp-esdoc?

I am using gulp-esdoc to generate my documentation (and it already works).
Today I added a git pre-commit hook, it launches multiples gulp tasks and prevent any commit if one of the tasks returns an error.
I works for most of my tasks, but for gulp-esdoc, I don't know how to return such an error to prevent the commit.
I configured my esdoc this way :
gulp.task('documentation', function() {
gulp.src("./client/")
.pipe(esdoc({
destination: "./docs",
"title": "SOMETHING",
index: "./README.md",
"plugins": [{
"name": "./README/docplugins/on-complete.js"
}]
}));
});
As you can see, I am using an esdoc plugin to do some code once the documentation has been generated, here is the code for the plugin :
var colors = require('colors'),
gutil = require('gulp-util');
exports.onComplete = function(ev) {
var output = require('../../docs/coverage.json');
var expectedCoverage = 100; // todo : get from option instead
var percentCovered = (output.actualCount / output.expectCount) * 100;
if (percentCovered < expectedCoverage) {
console.log('Code coverage is not sufficient (expected ' + expectedCoverage + '%, received only ' + percentCovered + '%) !!! Write some documentation or get out !'.red);
// return false; // todo
} else {
console.log('Code coverage is complete, well done :)'.green);
// return true;
}
};
The main goal here is to return an error if my code documentation is not 100% covered (the code logic is working, if a comment is missing in my JS code, I go into the line with the "todo".
Finally, here is my (simplified) git-hook (in my gulpfile) :
gulp.task('pre-commit', function () {
gulp.start('lint');
gulp.start('documentation');
});
The 'lint' part works, it prevent commit if I have an error in my code. But the 'documentation' code, using gulp-esdoc, doesn't return any error, so the commit is done :( I don't know what to do to return an error and prevent the git commit.
I need to do this because I want the junior developers joining my team to be forced to document their code :p
Thanks for helping !
One option is to throw a PluginError:
throw new gutil.PluginError('esdoc', 'Something broke');
This will cause your gulp process to exit with a non-zero exit code. It will however leave a rather ugly stack trace on STDERR (especially since gulp-esdoc rethrows errors from plugins).
Another option then is to explicitly exit the process with a specific exit code:
process.exit(1);
The process object in Node.js is a global object and can be accessed from anywhere without having to require() it.

Tridion 2011 SP1 : Tridion GUI Javascript error with Translation Manager and Powertools 2011 installed

I recently installed Tridion 2011 SP1 with SDL module Translation Manager enabled.
Everything was working fine. Then I installed the Tridion 2011 Powertools, following the installation procedure.
When trying to reload the GUI (browser cache emptied and modification parameter instanciated for server element in WebRoot\Configuration\System.Config) I'm getting the following Javascript error :
SCRIPT5007: Unable to get value of the property 'getItemType': object is null or undefined
Dashboard_v6.1.0.55920.18_.aspx?mode=js, line 528 character 851
And here is the concerned JS line:
Tridion.TranslationManager.Commands.Save.prototype._isAvailable=function(c,a){var
e=c.getItem(0),f=$models.getItem(e),b=f.getItemType(),d=$models.getItem(this.getTmUri ())
The preceding Javascript lines are dealing with other TranslationManager commands, so I suppose it is a kind of TranslationManager commands registration or somehting.
Trying to browse my Tridion publications by selecting any folder/strucutreGroup will also give the same error and the right frame (content frame) will not display any Tridion items but simply display:
Loading ...
Has anyone already experienced similar issue ?
For now I have no other choice than commenting out the Powertools sections file
Tridion_Home\web\WebUI\WebRoot\Configuration\System.Config
Thank you,
François
Strange thing here is that it refers to Save command which is not intended to be called or used from Dashboard.
I`d suggest to disable JS minification (JScriptMinifier filter in System.config), as it will probably show more correct details.
Another useful thing would be this error call stack.
--
I was not able to reproduce an issue from initial question, but had following error when I installed PT:
PowerTools is not defined
which appears in
*\PowerTools\Editor\PowerTools\Client\Shared\Scripts\ProgressDialog\ProgressDialog.js where it tries to register PowerToolsBase namespace, instead of PowerTools.
I`ll be surprised if adding
Type.registerNamespace("PowerTools");
at the top of the file will fix a problem, as in my case it was breaking entire GUI no matter if TM included or no.
I did check *\PowerTools\Editor\PowerTools\Client\Shared\Scripts\ProgressDialog\ProgressDialog.js, but the line
Type.registerNamespace("PowerTools");
was already there, so not the problem here.
Also, I disabled the JS minification. Here are the main methods the UI is loading before getting the error:
...
PowerTools.Commands.ItemCommenting.prototype.isValidSelection = function (selection) {
//Use the existing Save command from the CME
return $cme.getCommand("Save")._isEnabled(selection);
}
...
/**
* Executes this command on the selection.
* Override this method to implement the actual functionality.
* #param {Tridion.Core.Selection} selection The current selection.
*/
Tridion.TranslationManager.Commands.SendForTranslation.prototype._execute = function SendForTranslation$_execute(selection)
{
var selectedItems = selection.getItems();
if (selectedItems.length == 1)
{
var job = $models.getItem(selectedItems[0]);
if (job)
{
if (job.isLoaded())
{
job.saveAndSend();
}
else
{
$log.warn("Unable to send an unloaded job?! {0}".format(job.getId()));
}
}
else
{
$log.warn("Unable to execute save-and-send-for-translation for this selection: {0}".format(selectedItems));
}
}
else
{
$log.warn("Unable to save-and-send-for-translation multiple items at a time.");
}
};
...
Tridion.TranslationManager.Commands.Save.prototype._isAvailable = function Save$_isAvailable(selection, pipeline)
{
var itemUri = selection.getItem(0);
var item = $models.getItem(itemUri);
var itemType = item.getItemType(); !!!!!!!!! fails on this line !!!!!! item is null or not an object
var config = $models.getItem(this.getTmUri());
if (pipeline)
{
pipeline.stop = false;
}
if (config && config.hasChanged() && (itemType == $const.ItemType.CATEGORY || itemType == $const.ItemType.FOLDER || itemType == $const.ItemType.STRUCTURE_GROUP || itemType == $const.ItemType.PUBLICATION))
{
if (pipeline)
{
pipeline.stop = true;
}
return true;
}
return this.callBase("Tridion.Cme.Command", "_isAvailable", [selection, pipeline]);
};
Ok. It`s clear now.
PowerTools.Commands.ItemCommenting is used in Dashboard Toolbar.
This command uses Save to check its availability.
In the same time TM thinks that "Save" will only be used on an ItemToolbar.
The difference between this toolbars which cause an issue is that Dashboard view could have any-length selection, when Item view will always have selection having one item (currently opened).
Opening empty dashboard selection is not yet made, ItemCommenting tries to check its availability, by calling Save, which calls all its extensions. And so far as selection is empty
var itemUri = selection.getItem(0);
will return null, as well as
$models.getItem(null)
What you can do, is to remove ItemCommenting extension command as it is done in tridion powertool trunk editor.config.
http://code.google.com/p/tridion-2011-power-tools/source/browse/trunk/PowerTools.Editor/Configuration/editor.config?spec=svn942&r=903 [592]

SharePoint 2010 client javascript code from dialog box page

I am using code in an aspx page (javascript) that is displayed using the sharepoint 2010 UI framework dialog functions.
However, it throws an error. I can't get at the exact details. But here's the code
function DoReject(rejectype) {
rejecttype = rejectype;
this.clientContext = new SP.ClientContext.get_current();
var targetList = clientContext.get_web().get_lists().getByTitle('Applications');
var qs =window.location.search.substring(1);
var arrs = qs.substring(0,qs.indexOf('&',0)).replace('arr=','').split(',');
for (var i = 0; i < arrs.length;i++) {
k = arrs[i];
if (k != null && k != '') {
try {
this.applicant = targetList.getItemById(k);
applicant.set_item('ApplicationStatus', 'REJECTED');
applicant.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.doNothingReject), Function.createDelegate(this, this.rejectError));
this.applicant = targetList.getItemById(k);
clientContext.load(applicant, 'EMail', 'CrisDBID', 'ApplyJobTitle', 'JobRef', 'BrandId');
clientContext.executeQueryAsync(Function.createDelegate(this, this.DoRejectSuccess), Function.createDelegate(this, this.rejectError2));
}
catch (e) {
alert(e);
}
}
}
}
Note i haven't included the success / error methods, as they are superfluous in this. And the ids return correctly - they are passed into the query string. So the variable k is definitely the id of the list item.
In the error event rejectError, I use the signature
rejectError(e)
Does anyone know how to get the error details from the parameter / whats wrong with the code?
is it possible to call list operations on a page that isn't the native list page using the javascript object model?
thanks in advance
M
What browser do you get the error in? Is the error consistent between browsers? I would recommend that you debug the javascript and look at the variables at the line before it fails to see what's going on.
On a side note the first snippet you pasted looks like a standard train-wreck so if the code fails there it's likely one of these are undefined (if clientContext, get_web() or get_lists() does not return a value). I don't know anything about Sharepoint UI framework so "list operation" etc doesn't say much to me.

Categories