-
• #2
Hmm first guess is you need to create an instance of your jstools "class" with new.
var JsTools = require('jstools'); var jt = new JsTools(); setTimeout(function() { jt.setTimeByUrl('http://www.espruino.com', 1, console.log); }, 1000);
Not tested... but should work :)
-
• #3
thanks for your suggestion, this is the output
Uncaught Error: Function "setTimeByUrl" not found!
at line 1 col 4
jt.setTimeByUrl('http://www.espruino.com', 1, console.log);
^
in function called from system -
• #4
Oh i made a mistake.. try to change the require statement to this..
var JsTools = require('./jstools');
If the module is in the same directory of course. Important point is to provide the path (absolut or relative) to the module.
-
• #5
Thanks, just got it.
just export each function and that's it.
// module jtools.js exports.setTimeByUrl = function(url,tz,callback) { require('http').get(url, function(res){ var date = new Date(res.headers.Date); if (date > 0 ) { setTime(date/1000); E.setTimeZone(tz); error = null; } else { error = 'no date'; } if (callback) callback(error); }); };
// test module jtools.js var jt = require('jstools'); jt.setTimeByUrl('http://www.espruino.com',1,function(e){console.log(e);});
and no more erros :)
-
• #6
Exporting each function removes the need to instantiate with new but should not change the mistake i made with the require. Very Strange.. but glad it works now :)
-
• #7
The require('jstools') works because working with the WebIDE and store the jstools.js file in the module directory of my working project.
-
• #8
Ah this explains it.. i develop my modules in a IDE and serve them via a server on localhost.
Then i require them via URL when i want to test them in the WebIDE. -
• #9
There's some info on making modules here: http://www.espruino.com/Writing+Modules
It's for the website, but that way of working can go equally well when trying to build a module in.
But yes, the main thing is anything you want to access directly should just be
exports.xyz = ...
.One other thing to note: If you're trying to do arrays in a built-in module, try and do them inside a function where possible:
exports.getMyArray = function() { return [....] };
stores the function text in flash until it's executes, butexports.myArray = [....];
will put the array in RAM as soon as you first callrequire(...)
and will keep it there
The plan is to write a module and include it in custom build with JSMODULESOURCES to have all nice tools in place without wasting time on load.
Starting with a time helper as sample, I was fiddling around and have no clue how to write a working module. Any suggestions how to make this work?