GithubHelp home page GithubHelp logo

neonious / lowjs Goto Github PK

View Code? Open in Web Editor NEW
1.3K 43.0 72.0 1.58 MB

A port of Node.JS with far lower system requirements. Community version for POSIX systems such as Linux, uClinux or Mac OS X.

Home Page: http://www.lowjs.org/

License: Other

Makefile 0.38% C 7.79% JavaScript 44.61% C++ 45.52% HTML 0.01% TypeScript 1.39% Shell 0.11% SCSS 0.19%

lowjs's Introduction

lowjs

low.js is a free to use and open sourced port of the JavaScript runtime Node.js with far lower system requirements, allowing it to run on cheap, power-efficient microcontroller boards based on the ESP32-WROVER module. It also runs on Linux based systems as a smaller, faster booting alternative to Node.JS.

For more information on low.js, please visit http://www.lowjs.org/ .

This repository neither includes the ESP32 internals nor the neonious IDE. Thus, most development happens outside of the repository. Thus, see the Change Log for more activity.

First steps

To try out low.js on a PC, try out the chat webserver example in the repository, which you can run with both low.js and Node.js.

To try out low.js on a ESP32-WROVER, try out the examples on our homepage on your own board.

Compile from source

In case the binary distributions do not fit your needs, you can compile from source.

Before compiling, make sure you have the following software installed:

make g++
automake autoconf libtool
cmake
python py-pip
nodejs
npm (if not already installed together with nodejs)

Note: Node.js is only used to transpile the low.js libs from ES6 to ES5. It is only need for the build process. The binary distributions of low.js available on http://www.lowjs.org/ do not include Node.js, of course - this would defeat the purpose.

With this software installed, please install pyyaml with pip:

pip install pyyaml

The compilation itself can be done with these commands:

git clone --recurse-submodules https://github.com/neonious/lowjs
cd lowjs
make

low.js is now built in bin and can be called via bin/low.

The lib directory is also required for low to work (it accesses it via path_to_bin/../lib) and must be copied when creating a distribution. When creating a distribution, it might also make sense to strip the binary with the strip command, to save some KB.

Running tests

Please see the lowjs test documentation.

License / Authors / Contributions

We appreciate every person or company who is willing to contribute to low.js and its related products. We will gladly accept any code contribution which helps the cause after an appropriate review. Bug reports and suggestions are also welcome!

low.js, with exception of the adaption for ESP32, is placed under a permisse free license, allowing you to use low.js commercially and even modify it (see LICENSE file for details). The adaption of low.js for ESP32 is not Open Source, but may be used freely with the lowsync flashing tool. low.js is maintained by neonious, the makers of the neonious one microcontroller board.

Contact us

neonious GmbH
Münsterstr. 246
40470 Düsseldorf
Germany

https://www.neonious.com/
[email protected]

TEL +49 211 9241 8187
FAX +49 211 9241 8172

Managing Director / CEO: Thomas Rogg
District Court Düsseldorf, HRB 83086

Node.js is a trademark of Joyent, Inc. (https://www.nodejs.org/). ESP32 and ESP32-WROVER are products by Espressif Systems (https://www.espressif.com/). neonious GmbH is in no way affiliated with these companies.

lowjs's People

Contributors

dependabot[bot] avatar fc92 avatar hypfer avatar janus avatar jirutka avatar kennell avatar stevefan1999-personal avatar styfle avatar thomasrogg avatar wiktor-k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lowjs's Issues

From example: https_server.js

First of all, great work on simplifying nodejs. While I try to run some examples on my macOS, I see inconsistencies in https_server.js

var options = {
key: fs.readFileSync(path.join(__dirname, 'client.key')),
cert: fs.readFileSync(path.join(__dirname, 'client.crt'))
};

It should be

var options = {
key: fs.readFileSync(path.join(__dirname, 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'server.crt'))
};

Then rename client.key and client.crt to server.key and server.crt

Reasons: running a https server required server certificate, not client

Docs/examples for using packages (eg, websockets)

Hi there,

I've been trying to figure out how I'd go about using a package/module such as ws or socket.io-client to connect to a WebSocket I run on another server. While the documentation does indicate that node_modules is not supports, the web server example does require several modules. How can I do that for another module?

Basically I'm trying to set up my device (Neonious One) as a small client for receiving messages via socket to set various pins high or low to control relays etc. I'd run the socket server and the UI app elsewhere.

Thanks!

Map and Set objects are not identified correctly

Extracted from #29 (comment)

Just FYI, there is a similar issue in React Native's runtime: facebook/react-native#19594

// Common stuff that works:
Object.prototype.toString.call(new Array())
// [Object Array]
Object.prototype.toString.call(new Date())
// [Object Date]

// Map and Set don't work:
Object.prototype.toString.call(new Set())
String(new Set())
// [Object object] but should be [Object Set]

Object.prototype.toString.call(new Map())
String(new Map())
// [Object object] but should be [Object Map]

This self-identification of constructors in JS is used quite frequently. If it is incorrect hacks have to be used.

Set: TypeError: Invalid attempt to spread non-iterable instance

I'm using Babel 7, maybe there is an incompatibility with the polyfills provided by low.js?

TypeError: Invalid attempt to spread non-iterable instance
    at _nonIterableSpread (/home/mha/neo/DEVICE/node_modules/@babel/runtime/helpers/nonIterableSpread.js:2)
    at _toConsumableArray (/home/mha/neo/DEVICE/node_modules/@babel/runtime/helpers/toConsumableArray.js:8)
    at _send (/home/mha/neo/DEVICE/node_modules/one/lib/message-bus.js:68) strict tailcall
    at _callee2$ (/home/mha/neo/DEVICE/node_modules/one/lib/instance.js:73) strict
    at tryCatch (/home/mha/neo/node_modules/regenerator-runtime/runtime.js:62) strict
    at invoke (/home/mha/neo/node_modules/regenerator-runtime/runtime.js:288) strict tailcall
    at asyncGeneratorStep (/home/mha/neo/DEVICE/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3)
    at _next (/home/mha/neo/DEVICE/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25)

Code in one/lib/message-bus.js produced by Babel 7:

  var typeHandler = handlers.get(type);

  if (typeHandler instanceof Set) {
    callbacks.push.apply(callbacks, (0, _toConsumableArray2.default)(typeHandler.values()));
  }

Let's follow what happens down in _toConsumableArray2 and below in the Babel helpers. Code in @babel/runtime/helpers/toConsumableArray.js:8:

var arrayWithoutHoles = require("./arrayWithoutHoles");

var iterableToArray = require("./iterableToArray");

var nonIterableSpread = require("./nonIterableSpread");

function _toConsumableArray(arr) {
  return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}

module.exports = _toConsumableArray;

So that ends up failing in iterableToArray, because the final call to nonIterableSpread() has only a single active line of code, which is the throw instruction for the error.

Code in @babel/runtime/helpers/iterableToArray.js that should have worked but failed:

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

module.exports = _iterableToArray;


PS: I'm a little stubborn with Babel 7, vs. the Babel 6 currently used by lowsync (or even TS), because... what else would one use in almost 2019? It was a major upgrade awaited for years, should I really optimize anything for Babel 6 at this point? No :-)

Wifi not available

Hey everyone,

I would like to use low.js to start an IoT project using node.js. After flashing the firmware with lowsync flash /dev/cu.SLAB_USBtoUART --init I'm getting an outpot with wifi information. The problem here is that the wifi is not available. It simply doesn't exist.

~ ❯❯❯ lowsync flash /dev/cu.SLAB_USBtoUART --init                                                                                                                                  ⏎
*** Step 1/3: Probing ESP32 microcontroller
*** Step 2/3: Erasing flash and downloading image in parallel
esptool.py v2.6-beta1
Serial port /dev/cu.SLAB_USBtoUART
Connecting........_
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: 3c:71:bf:48:45:dc
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Erasing flash (this may take a while)...
Chip erase completed successfully in 6.9s
Hard resetting via RTS pin...
*** Step 3/3: Flashing image
esptool.py v2.6-beta1
Serial port /dev/cu.SLAB_USBtoUART
Connecting........___
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: 3c:71:bf:48:45:dc
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 32768 bytes to 9486...
Wrote 32768 bytes (9486 compressed) at 0x00001000 in 0.1 seconds (effective 2166.0 kbit/s)...
Hash of data verified.
Compressed 3080192 bytes to 1175481...
Wrote 3080192 bytes (1175481 compressed) at 0x00010000 in 20.1 seconds (effective 1222.9 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...
*** Done, low.js flashed, now in factory state
To communicate with your microcontroller, connect to the Wifi:
SSID:       low.js@ESP32 3C71BF4845DC
Password:   ********
In this Wifi, the microcontroller has the IP 192.168.0.1

Do you have any idea why the wifi is not available and how I may fix it?

Thanks a lot!

fs.util's promisify() method exists but causes error in DukTape

"util" is green on https://www.lowjs.org/documentation/nodejs-api.html and promisify exists.

I tried promisifying a few functions in fs and got

> var readFile = promisify(fs.readFile);
TypeError: undefined not callable (property 'getOwnPropertyDescriptors' of [object Function])
    at [anon] (deps/duktape/src-low/duktape.c:64945) internal
    at promisify (lib:internal/util:294) strict
    at global (repl:1) preventsyield
    at [anon] () native strict preventsyield
    at [anon] (lib:vm:26) strict
    at defaultEval (lib:repl:260) strict
    at onLine (lib:repl:511) strict
    at emit (lib:events:158) strict
    at [anon] (lib:readline:231) strict
    at [anon] (lib:readline:530) strict
    at [anon] (lib:readline:773) strict
    [...]

PS: This is not urgent, I was just curious and experimenting.

key values in every Array

The code

var friends = [];
friends['Thomas'] = 1;
friends['Felix'] = 1;
console.log(friends);
for (var key in friends) {
console.log('key:' + key);
}

produces the output

[18:40:57] [ Thomas: 1, Felix: 1 ]
[18:40:57] key:Thomas
[18:40:57] key:Felix
[18:40:57] key:values

Unexpected behavior while play with low_add_stash

Noticed that is one includes PRINTF statement inside the below function, it becomes extremely hard f for one to use repl, ie JS at the console. Is this a bug or that is the effect of threads?

int low_add_stash(low_main_t *low, int index)
{
if(low->duk_flag_stop)
return 0;

duk_context *ctx = low->stash_ctx;
if(duk_is_undefined(ctx, index))
    return 0;

duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, "low");

//printf("%d", index);
int stashIndex;
while(true)
{
stashIndex = ++low->last_stash_index;
if(!stashIndex)
stashIndex = ++low->last_stash_index;

    if(!duk_get_prop_index(ctx, -1, stashIndex))
    {
        duk_pop(ctx);
        break;
    }
    duk_pop(ctx);
}

duk_dup(ctx, index);
duk_put_prop_index(ctx, -2, stashIndex);
duk_pop_2(ctx);

return stashIndex;

}

I2C usage

Hey guys, unfortunately I wasn't able to figure out how the I2C module with lowjs works. Normally these i2c packages have methods like writeByte and readByte but here it seems to be transfer only. May you give an example for it? That would be very kind of you.

Thanks you very much!

simple issue with vm

Code:

const vm = require('vm');

global.globalVar = 0;

const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
var i;
for (i = 0; i < 1000; ++i) {
  script.runInThisContext();
}

console.log(globalVar);

Result:

TypeError: cannot read property '_vmIsRunning' of undefined
at [anon] (deps/duktape/src-low/duktape.c:56562) internal
at [anon] (lib:vm:17) strict tailcall
at [anon] (/Users/thomas/test2.js:8) preventsyield

Install issue Linux Mint 18.3.

Howdy,
I had some serious issues with the nodejs and npm install just to get as far as I got.
That was some serious digging.
Anyway, now I am at the stage where I try to install lowsync and get this error:

lowsync flash /dev/ttyUSB0 --init

/usr/local/lib/node_modules/lowsync/build/index.js:177
        Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
                                       ^
SyntaxError: Unexpected token .
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:442:10)
    at startup (node.js:136:18)
    at node.js:966:3

Nodejs is at v4.2.6.
Npm is at 3.5.2.

Why using index 0 when matching with index 1

In the second IF ELSE statement why using
LowDataCallback *elem = low->data_callback_first[0]; instead of
LowDataCallback *elem = low->data_callback_first[1];

void low_data_clear_callback(low_main_t *low, LowDataCallback *callback)
{
pthread_mutex_lock(&low->data_thread_mutex);
if(low->data_callback_first[0] == callback)
{
LowDataCallback *elem = low->data_callback_first[0];
low->data_callback_first[0] = elem->mNext;
if(!low->data_callback_first[0])
low->data_callback_last[0] = NULL;
}
else if(low->data_callback_first[1] == callback)
{
LowDataCallback *elem = low->data_callback_first[0];
low->data_callback_first[1] = elem->mNext;
if(!low->data_callback_first[1])
low->data_callback_last[1] = NULL;
}

Value of event loop references counter (low->run_ref) can be incorrect

That case can be reproduced by executing this script on low.js under Linux :

const fs = require("fs");

const testCount = 512;
var openCount = 0;
var closeCount = 0;

for (var i = 0; i < testCount; i++) {
    fs.open("/etc/hosts", "r", function (err, fd) {
        if (err) console.log(err);
        else {
            openCount++;
            fs.close(fd, function (err) {
                if (err) console.log(err);
                else {
                    closeCount++;
                    if (closeCount == testCount) console.log("openCount=" + openCount + ", closeCount=" + closeCount);
                }
            });
        }
    });
}

The expectation is, that program display openCount=512, closeCount=512 and terminate, but event loop does not exit, and low->run_ref have quite random value like -17 or 3.

None of testCount (besides of 1) values does not guarantee correct behaviour - when it's higher, problem is more evident.

Documentation: timeline for in-development/upcomming features

I need some Node API that at the moment are not implemented or partially implemented (TLS and Crypto), to have a public timeline of developing milestones will be useful not only for me but for the community waiting for some API to start their projects/products.

low.js binary enters busy loop when I do "require("core-js/fn/set");"

Command in the low.js REPL for easiest demonstration:

mha@mint-virtual-machine ~/neo/DEVICE $ ~/lowjs-linux-x86_64-20181223/bin/low 
> require("core-js/fn/set");

...and nothing. The process time keeps increasing steadily, but strace -p shows no activity. I cannot kill, I have to use kill -9.

core-js version is 2.5.7 (the version requested by the currently latest version of @babel/polyfill, Babel 7).

Cannot create Github issue

I tried creating an issue and it seemed to work twice, got nr. 24 and 25 respectively after submitting the new issue, but a second later the issues list did not show my new issue and when I reloaded the page I had just received after opening the new issue I got code 404 from Github - it had just disappeared....?

issue with repl and ctrl-c

After entering

require('dgram').createSocket('udp4').send('blafgddfgfgd', 12345);

in REPL, I have to press ctrl-c 3 times to get out of low. With Node.js it is only 2 times.

crypto: SHA-256 hashes in hex notation are not always 64 characters

Using low.js for Linux, downloaded 9 December, 2018: https://www.lowjs.org/downloads/lowjs-linux-x86_64-20181209.tar.gz

Apparently hex values like "0a" are written into the final SHA-256 hash as just "a" when the hash string is created from its components.

> mha@mint-virtual-machine ~/neo $ node
> const crypto = require('crypto')
undefined
> crypto.createHash('sha256').update("strin", 'utf8').digest('hex').length
64
> crypto.createHash('sha256').update("strin", 'utf8').digest('hex')
'98db433e68d56413cb026680937df70118070c105d0c8a74f4b6f8ec5ea140ee'

vs.

> var crypto = require('crypto')
undefined
> crypto.createHash('sha256').update("strin", 'utf8').digest('hex').length
62
> crypto.createHash('sha256').update("strin", 'utf8').digest('hex')
'98db433e68d56413cb026680937df7011807c105dc8a74f4b6f8ec5ea140ee'

For direct comparison, the missing "0"s shown as spaces:

98db433e68d56413cb026680937df70118070c105d0c8a74f4b6f8ec5ea140ee
98db433e68d56413cb026680937df7011807 c105d c8a74f4b6f8ec5ea140ee

PS: On the new https://www.lowjs.org/ I cannot find the Github link any more. EDIT: Ah okay, under Downloads. I think this should be a on the top of the page, many projects have it as part of the page header on all pages, to clearly show that it is open source.

Neonious one IDE: Session should not expire

Subject says it. The IDEs session should not expire.

Or not that quickly. And/or inform me when it happens, and not a long time after it happened when I try to save my work (now lost because I had to reload the page).

How to override require and require.resolve?

Following up on #9, I have successfully used an alternative implementation of require.resolve , yet from my experiments it is realized that the commonjs objects are actually immutable, making it impossible to rewrite their reference globally.

require.resolve = function(x) {
  return __require("resolve").sync(x, { preserveSymlinks: true });
};

__require = require;
require = new Proxy(require, {
  apply: function(target, thisArg, argumentsList) {
    return __require.apply(thisArg, argumentsList.map(require.resolve));
  }
});

// Actually require is distinct for each module!

I'm doing it on request of trying to use node_modules and starting to test low.js with standard node.js test suite.

Type issue with wifi password

When I try to set the wifi mode to station and pass a wifi password like wifi.password="11112222333344445555" I'm getting back an error saying that the given value (integer) is not valid for this setting. So I'm passing a string but it looks like internally its converted to integer which is a problem. Most FritzBoxes for example use a string of numbers as password.

Is it a problem in lowjs or the underlying system?

Thanks a lot!

low.js binary does not find local modules

Running node.js REPL I can require('some-local-package') and it is loaded. Doing the same using the low.js binary REPL I get (example)

> require('js-sha256')
TypeError: cannot resolve module 'js-sha256', parent '<repl>'
    at [anon] (src/low_module.cpp:456) internal
    at require () native strict preventsyield
    at global (repl:1) preventsyield
    at [anon] () native strict preventsyield
    at [anon] (lib:vm:17) strict
    at defaultEval (lib:repl:260) strict
    at onLine (lib:repl:511) strict
    at emit (lib:events:158) strict
    at [anon] (lib:readline:231) strict
    at [anon] (lib:readline:530) strict
    at [anon] (lib:readline:773) strict
    [...]

The modules are in node_modules in the current directory, which also is a project root.

Feature: Let the developers add their own Babel modules to a base-level configuration (+ Babel 7, which is already implemented)

Extracted from the discussion here (point 4 in the linked comment) and made into an issue because it is a feature request.

1

Both lowrmt and the browser IDE should use Babel (which gives TypeScript support for free too) instead of one using TS, the other one Babel 6.

2

Right now lowrmt (but also TS inside the browser IDE) have a hard-coded configuration.

lowrmt's Babel configuration: https://github.com/neonious/lowsync/blob/master/lowrmt/src/commands/commands/sync.ts#L417

Developers should be able to add additional Babel modules, e.g to support Flow types or later ECMAScript features.

Load node modules from SD card

Hey guys,

I'm currently experimenting a lot with low.js. I want to use some node modules which have a size of 9 MB total. For sure that amount of data must be stored on sd card. It looks like you haven't yet implemented filesystem symlinking so it seems to be impossible to load node modules from sd card.

This is my current code:

const sdcard = require('sdcard');
const fs = require('fs');

sdcard.mount(() => {
    fs.symlink('./sd/node_modules', './node_modules', () => {
        console.log('Node modules folder symlinked successfully');

        // When it's implemented I can load modules here with require()
    });
});

Do you have any workaround for it? Btw. I must do the sdcard.mount() thing. Otherwise ./sd is not mounted. Maybe due to a timing issue which starts index.js before SD card has been mounted.

Close method returns only 'true'

I can't figure out how this method would return false.
``
bool LowFile::Close(int callIndex)
{
if (mClose)
{
duk_dup(mLow->duk_ctx, callIndex);
low_push_error(mLow, EBADF, "close");
duk_call(mLow->duk_ctx, 1);
return true;
}
if (mPhase != LOWFILE_PHASE_READY)
{
duk_dup(mLow->duk_ctx, callIndex);
low_push_error(mLow, EALREADY, "close");
duk_call(mLow->duk_ctx, 1);
return true;
}
// We must no longer advertise, so we do not remove other persons FD later on
int fd = FD();
SetFD(-1);
AdvertiseFD();
SetFD(fd);

if (callIndex != -1)
{
    mCallID = low_add_stash(mLow, callIndex);
    if (mCallID)
        mLow->run_ref++;
}
else
    mCallID = 0;

mPhase = LOWFILE_PHASE_CLOSING;
mDataDone = false;
low_data_set_callback(mLow, this, LOW_DATA_THREAD_PRIORITY_READ);

return true;

}
``

IDE: "File Explorer" does not show all files

I ran the mini app test and it works now, but if I want to check if the files it was supposed to create were in fact created I have to do a lowsync sync to sync them back from the device into the PC sync directory. Looking at the file system with the IDE's "File Explorer" show the directories under "/DATA/...", but the directories are shown as empty. They contain 64 hex-character named files without extension, e.g. "44af76dd9c44e044d2346c4eac40e4aaff08f2f163573181939e8521ea29f8d7". Those are (UTF-8) text files stored under the SHA-256 of their contents.

Does the File Explorer filter the list of files that it displays?


PS: Latest code sent as link to archive, just FYI, I guess you can answer this one without having to execute anything. I changed the code to limit the path length as advised.

ArmV5 support please

I realize this is a rather archaic architecture at this point, but would an ArmV5 (running linux) be doable ?

Crash on Neo One device (no output)

I just replaced the entire existing demo code with our own stuff, which does not start a webserver. Now I can't reach the device (not a hard issue, factory reset works because this time the firmware works).

Do I have to have a webserver running from my code, even if I don't need it? If that is so, there seems to be some minimum code that always has to be present, which should be documented. I wish lowsync commands would still work (start, stop, status, sync, monitor) regardless of what my code does. My test ran some batch stuff, just create some files, and then it stopped (I think, I don't know, I can't access the device any more).

PS: In our app there will only be websocket connections, no webserver.

DIfferent behavior of fs.readdir on node.js vs. low.js

Example, running the following in a random directory:

fs.readdir('.', function (err, files) {console.log(err, files);})

node.js 11.5.0 output:

[ 'DATA',
  'index.js',
  'node_modules',
  'polyfills.js',
  'register-types.js' ]

lowjs-linux-x86_64-20181223 output:

[ 'node_modules',
  '..',
  'index.js',
  'register-types.js',
  '.',
  'DATA',
  'polyfills.js' ]

TypeError: cannot find module 'lib:init'

Trying to run @rxdi/core with low.js and i am facing the following error:

TypeError: cannot find module 'lib:init'
    at [anon] (src/low_module.cpp:226) internal
Segmentation fault (core dumped)

https://github.com/rxdi/core/tree/master/dmodule

Btw @rxdi/core can be found on decentralized space:

https://ipfs.infura.io/ipfs/QmP9n7m1UWkFn2hqt7mnfQYnBtxmFyyvKZHN7hgngQb1gM

Here is a module which is working on regular Typescript compilation to commonjs module.

Any ideas ?

DukTape error: "unsupported"

Babel (7.2), using only "preset-env" without options (e.g. no "target"), produced this code, all functions at the top are Babel helpers:

'use strict';

// BABEL INTERNAL HELPERS

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

// ACTUAL CODE STARTS HERE

var FileNotFoundError = function (_Error) {
  _inherits(FileNotFoundError, _Error);

  function FileNotFoundError(file, type) {
    var _this;

    _classCallCheck(this, FileNotFoundError);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(FileNotFoundError).call(this, 'File not found: ' + file + ', type "' + type + '"'));
    _this.name = 'FileNotFoundError';
    _this.file = file;
    _this.type = type;
    return _this;
  }

  return FileNotFoundError;
}(_wrapNativeSuper(Error));

// DukTape error "unsupported"
new FileNotFoundError('filename', 'type');

Result of running this with lowjs-linux-x86_64-20181209:

Error: unsupported
    at [anon] (deps/duktape/src-low/duktape.c:62867) internal
    at _construct (/home/mha/neo/DEVICE/node_modules/one/lib/storage-base-common.js:12) strict tailcall
    at FileNotFoundError (/home/mha/neo/DEVICE/node_modules/one/lib/storage-base-common.js:27) strict construct
    at [anon] (/home/mha/neo/DEVICE/node_modules/one/lib/storage-base-common.js:37) strict preventsyield

The original ES 2015 code for the class (two or three custom errors are the only uses of classes in our code, everything else is "just functions and objects"):

class FileNotFoundError extends Error {
    constructor (file, type) {
        super('File not found: ' + file + ', type "' + type + '"');
        this.name = 'FileNotFoundError';
        this.file = file;
        this.type = type;
    }
}

spi module not found from TypeScript

We just got a few neonious one for a hackathon and I wanted to try the TypeScript support in the IDE, but I'm failing to import the ESP32-specific modules like 'spi'. Standard modules like 'http' seem to work fine

import * as http from 'http';
http.createServer(function(req, res){res.end();});

import * as spi from 'spi';

let s = new spi.SPI({pinSCLK:7, pinMOSI:6});
s.transfer(Buffer.from([0x00, 0x00, 0x00, 0x00]));

Fails with Cannot find module 'spi'. (4, 22).

The equivalent JavaScript (which is basically the same as the transpiled code) works as expected.

Am I missing something? The documentation does not really mention TypeScript at all...

node.js compatibility: things I miss in the "fs" module

There is an object with constants on require('fs').constants in node.js

https://nodejs.org/api/fs.html#fs_fs_constants_1

I'm using them in fs method calls, for example fs.access(file, fs.constants.F_OK, function (err) {...

Other node.js fs functions I use that are missing in low.js:

  • fs.constants (I only use F_OK and only with fs.access)
  • fs.access() (only for checking file existence, see the note at the end)
  • fs.readdir()
  • fs.appendFile() (JS-code convenience function in node.js using fs.writeFile)
  • fs.mkdir()

I can replace my file existence check, which uses fs.access and fs.constants with an attempt to fs.read. I think readdir and mkdir might not be too complicated to add? I can of course replace fs.append by fs.writeFile with an "append" option since its only in the node.js API for convenience (I hope low.js supports the "append" flag).

So the only ones I don't have a workaround for are readdir and mkdir.

I use fs.access to check existence (without doing anything else to the file, really just a pure existence check) because node.js docs say so: https://nodejs.org/dist/latest-v11.x/docs/api/fs.html#fs_fs_stat_path_options_callback

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

Issue with uart module and ESP32

Hi,

I'm new to low.js and I'm trying to run a simple "Hello world" program.
For that effect, I'm trying to import the 'uart' module to write some content to the serial port.

Nonetheless, when I import it, the program seems to stop working correctly.

For example, the code below works well and turns on my board's LED:

let gpio = require('gpio');

let state = 1;
gpio.pins[21].setType(gpio.OUTPUT).setValue(state);

setInterval(() => {}, 100);

If I add the import of the 'uart' module, then the LED no longer turns on, thus seeming to be causing some problem in the program.

let uart = require('uart');
let gpio = require('gpio');

let state = 1;
gpio.pins[21].setType(gpio.OUTPUT).setValue(state);

setInterval(() => {}, 100);

I probably just missed some detail on the documentation, but if you could give me some help it would be awesome :)

Board: ESP32 TTGO T8 V1.1 (ESP32-WROVER module)

Best regards,
Nuno Santos

Plans to open source the ESP32 adaptation?

Hi folks,

Like the title says - are there any plans to release the source code for adaptation of low to the ESP32 platform? And what would it take do so if not? I believe this would be a great start for new projects given the quality of the code I’ve seen thus far in the project.

Thanks

Documentation: How to run mocha tests using low binary instead of node

Before I run code on the device I would like to use the platform binary or low.js to run the transpiled code on the development system. Specifically and as a use case example, I want to run the existing mocha tests (used for node.js and browser thus far).

This does not seem to be trivial, I can't find a way to run mocha tests on low. I would appreciate this added to documentation. Automated tests are a must, how would one use one of the most widely used tets runners with low.js?

Related: svaarala/duktape#1549

Feature: function.toString()

We are actually using the toString() method on functions to get the source code of functions. On low.js I always get

'function myFunction() { [ecmascript code] }'

EDIT:

Just FYI, I can work around this, in fact I may remove our option to store function code entirely. Still, that's what current JS spec wants, ES 2015+ so I'll leave this for the backlog queue.

Question: Compatibility with C++ node modules

First of all, bravo for this amazing project. I find it to be the most interesting project of the year!

Then, I saw that you have support for importing node modules (example with ws). Would you be able to support a C++ based library such as uWebSockets?

Do you have support for the V8 engine?

Documentation: Babel configuration?

I would like to know from somewhere what Babel settings are required. It does not seem to be completely straightforward, with some features supported natively but most not.

List of "post ES5" features I woudl not need to Babel: https://wiki.duktape.org/PostEs5Features.html

So... this looks like a complex Babel setup. I think there should really be an example. Since the IDE does transpilation, what does it use?

Assuming people using Babel 7 and ES 2017; the new Babel version because it was such a big and long-planned step from Babel 6, and ES 2017 because downgrading is easy.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.