NodeRT - StorageFile.openAsync returns undefined fileStream, but no error - node.js

I'm just getting started with NodeRT & Electron (Windows 10). Some of the basics seem to be working, but I've quickly run up against a strange issue. Here's the code:
const {FileAccessMode, StorageFile} = require('electron').remote.require('#nodert-win10/windows.storage')
var fname = require('electron').remote.app.getPath('userData') + '\\test.jpg';
StorageFile.getFileFromPathAsync(fname, (err, storageFile) => {
if (err) return console.log(err);
storageFile.openAsync(FileAccessMode.read, (err, fileStream) => {
if (err) return console.log(err);
// fileStream is NULL HERE!
})
})
getFileFromPathAsync succeeds and the resulting storageFile is valid. However, openAsync returns an undefined fileStream and an undefined err!
Questions:
What am I doing wrong here?
In any case, why is openAsync failing silently with no error?
Thanks!

Finally, this was a bug in NodeRT when used in combo with the most recent electron builds. It is now fixed.
Props to #nadavbar for fixing this the same day that I reported it. :) NodeRT seems to play very nicely with electron now.

Related

Electron issue after updating electron and typescript

I have a small electron project which I've just updated (Electron, typescript etc)...
This is the code that's breaking:
dialog.showOpenDialog({}, (files) => {
if(files && files.length > 0) {
fs.readFile(files[0], 'utf8', (err, res) => {
if (!err) {
editor.setModel(monaco.editor.createModel(res, 'javascript'));
}
})
}
})
It doesn't like the {} after dialog.showOpenDialog(
The error I'm getting is:
Argument of type '{}' is not assignable to parameter of type 'BrowserWindow'.
How can I fix this?
The showOpenDialog is used differently, probably you updated from a quite old electron version and they changed it. Now it takes an optional browserWindow and an options object and returns a promise (shown with the async/await syntax):
const {canceled, files, bookmarks} = await dialog.showOpenDialog({});
Reference: https://www.electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

How to fix: Error: If .NET source is provided as JavaScript function, function body must be a /* ... */ comment

I am trying to run the basic hello world example from the documentation from here (it's the first example on the page):
https://github.com/agracio/edge-js
I have a typescript file that I am running (see the code below). I am on node version 9.9.0 on a Windows 10 64 bit. I have made only the following installations:
npm install edge
npm install edge.js
npm install #types/node --save-dev
I have made the installations to the same directory as the typescript file.
I am able to run ts-node app.ts in the command line and have it console.log("hi") successfully in that directory.
However, when I change my code to the example below, it is giving me the error throw new Error('If .NET source is provided as JavaScript function, function body must be a /* ... */ comment.');
I had originally tried doing this using edge.js but I kept getting the error that I needed to precompile. For the life of me I couldn't get it to find my python executable when executing build.bat release 10.5.3. (Despite including an environment variable PYTHON with a value of c:\Python\Python37\python.exe) I wanted to try using edge-js because it was already precompiled. I downgraded node to 9.9 (I uninstalled node 10.15.3 and then installed the 9.9.0 msi from the website) because I thought edge-js only supported version 9. Well here I am trying to run edge-js with version 9 and I am still getting an error, although it is a different error.
Here is the code I am trying to run:
var edge = require('edge-js');
var helloWorld = edge.func(function () {/*
async (input) => {
return ".NET Welcomes " + input.ToString();
}
*/});
helloWorld('JavaScript', function (error, result) {
if (error) throw error;
console.log(result);
});
I can't believe this worked. It was a syntax error. A problem with the amount of whitespace between the comment and the end of the function. Here is the correct syntax:
var edge = require('edge-js');
var helloWorld = edge.func(function () {
/*async (input) => {
return ".NET Welcomes " + input.ToString();
}*/
});
helloWorld('JavaScript', function (error, result) {
if (error) throw error;
console.log(result);
});

nodeschool:learnyoumongo "FIND" lesson fails before I write anything - config?

Currently the only thing I have in my file is the following:
var mongo = require('mongodb').MongoClient,
url = 'mongodb://localhost:27017/learnyoumongo';
console.log(mongo);
When I run the verify command, I get the following error:
/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37
db.collection('parrots').remove({}, function(err) {
^
TypeError: Cannot read property 'collection' of undefined
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37:5)
at next (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:260:17)
at Exercise.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:266:5)
at Workshopper.end (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:191:12)
at Workshopper.done (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:323:19)
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:149:14)
at /usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:136:16
at Exercise.<anonymous> (/usr/local/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/filecheck.js:10:14)
at FSReqWrap.oncomplete (fs.js:95:15)
When I took a look at the exercises.js file, I see the error is pointing to the .addCleanup function and the db it is trying to close is undefined.
This seems like a connection/configuration error, but I passed the first two modules. Can anyone help?
Update
This is definitely a connection error. The previous scenario was created using the command in the workshop module mongod --port 27017 --dbpath=./data, however when I opened a new terminal tab and just ran mongo without any arguments, the verify command actually output the "Actual/Expected" evaluation and module results.
To the user who asked for the rest of the script, please understand if you are unfamiliar with nodeschool that this is an entire repository with module based automated/interactive tutorials, so this is not all of the code. In any case, here is what you requested:
var mongo = require('mongodb').MongoClient
, exercise = require('workshopper-exercise')()
, filecheck = require('workshopper-exercise/filecheck')
, execute = require('workshopper-exercise/execute')
, comparestdout = require('workshopper-exercise/comparestdout')
exercise = filecheck(exercise)
exercise = execute(exercise)
exercise = comparestdout(exercise)
var db, url = 'mongodb://localhost:27017/learnyoumongo'
exercise.addSetup(function(mode, cb) {
var self = this
this.submissionArgs = [3]
this.solutionArgs = [3]
mongo.connect(url, function(err, _db) {
if (err) return cb(err)
db = _db
col = db.collection('parrots')
col.insert([{
name: 'Fred'
, age: 1
}, {
name: 'Jane'
, age: 3
}, {
name: 'Jenny'
, age: 10
}], cb)
})
})
exercise.addCleanup(function(mode, pass, cb) {
db.collection('parrots').remove({}, function(err) {
if (err) return cb(err)
db.close()
cb()
})
})
module.exports = exercise
I think that should be:
var mongo = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/learnyoumongo', function(err, db) {
console.log(err);
});
There was definitely a connection problem. I'm not sure exactly where the bug was, but I reloaded learnyoumongo and reinstalled a couple of node packages. When I did that I had to go back and change permissions on the data directory again.
My recommendation if anyone else faces strange config errors, is to try to reinstall. Then when you connect, it doesn't hurt to re-verify the CONNECT module to make sure you have a good connection when you start your work space.

node.js + express error: cannot read property 'url' of undefined

I'm fairly new to Node.js, installing it to try out the DrupalChat (v7dev) module. I believe this problem is with either node.js or express, as I am beyond the stage where the chat module's settings are loaded. I am faced with the following output when trying to start the chat server
Extension loaded: drupalchat_nodejs.server.extension.js
Started http server.
info - socket.io started
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'url' of undefined
at Function.handle (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/proto.js:105:18)
at Server.app (/usr/local/lib/node_modules/npm/node_modules/express/node_modules/connect/lib/connect.js:60:31)
at Server.serverListening (/usr/local/lib/node_modules/npm/node_modules/socket.io/node_modules/policyfile/lib/server.js:136:16)
at Server.g (events.js:154:14)
at Server.emit (events.js:64:17)
at Array.1 (net.js:710:10)
at EventEmitter._tickCallback (node.js:192:40)
I remember when express installed, it gave a warning like ".... bugs['web'] should probably be bugs['url']" (I can't remember the prefix)
So is it that the server is trying to read an (API?) variable 'url' but its currently 'web'?
I have all the modules up to date, is it that I should downgrade? Or is there some way of working around this using another module?
EDIT:
line 201 is the last very line (delete authenticatedClients[authData.authToken];)... I just added to whole function for proper context
var authenticateClientCallback = function (error, response, body) {
if (error) {
console.log("Error with authenticate client request:", error);
return;
}
if (response.statusCode == 404) {
if (settings.debug) {
console.log('Backend authentication url not found, full response info:', response);
}
else {
console.log('Backend authentication url not found.');
}
return;
}
var authData = false;
try {
authData = JSON.parse(body);
}
catch (exception) {
console.log('Failed to parse authentication message:', exception);
if (settings.debug) {
console.log('Failed message string: ' + body);
}
return;
}
if (!checkServiceKey(authData.serviceKey)) {
console.log('Invalid service key "', authData.serviceKey, '"');
return;
}
if (authData.nodejsValidAuthToken) {
if (settings.debug) {
console.log('Valid login for uid "', authData.uid, '"');
}
setupClientConnection(authData.clientId, authData, authData.contentTokens);
authenticatedClients[authData.authToken] = authData;
}
else {
console.log('Invalid login for uid "', authData.uid, '"');
delete authenticatedClients[authData.authToken];
}
}
Per #thesnufkin's post, looks like the underlying express version currently pulled is not stable. Roll back to 2.5.9 and you should be good to go:
npm uninstall express
npm install express#2.5.9
As requested,
The v7 chat module from drupal is not stable. You should not use it in production.
Check bugs : http://drupal.org/project/issues/drupalchat?status=All&categories=All
Check forums : http://drupalchat7.botskool.co.in/?q=forum
Still looking for a new maintener:
"New maintainer wanted - please ping beejeebus if you're interested!".
nodejs module has this issue, so I don't think its related to the drupalchat server specifically. Here is the issue for that: http://drupal.org/node/1537702
The option to use node.js as backend in DrupalChat is currently under development. It also depends when (date on which) you downloaded the DrupalChat since the dev code is updated everyday, if new code is committed.
Please raise an issue for the same at this link - http://drupal.org/project/issues/drupalchat?status=All&categories=All.
Thanks,
darklrd

Resources