Massi
Posts: 1679
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Starting to fight with node..

Mon Sep 19, 2016 6:32 pm

Hello all (hello Heater :))

so i ended up installing node (6.5) just to have something to ask Heater :lol:

installation of node was incredibly simple. Good start.
Then i choose a random thing (in my case: serial port on a rfcomm serial) to test node.
And here starts hell :)
1) node modules are a jungla!! but eventually, i choosed "serialport". This seems ok. I discovered also "strange" params to get npm to work. To install serialport i had to use -g but also "--unsecure-perms". This seems stupid :)

2) an help with code is required, but i'll post later :)

3) how are permissions managed in node?? i mean, look at this:

Code: Select all

[email protected]:/usr/local/bin/classes/sensors $ node btpower.js
Port open
Port close
[email protected]:/usr/local/bin/classes/sensors $ sudo node btpower.js
module.js:457
    throw err;
    ^

Error: Cannot find module 'serialport'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/bin/classes/sensors/btpower.js:2:18)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
why??


and finally the code help :)
can anyone help me using the ByteLength parser?

if i use the code from the github page i get an error:

Code: Select all

var ByteLength = SerialPort.parsers.ByteLength
var parser = port.pipe(new ByteLength({length: 8}));
gives

Code: Select all

var parser = port.pipe(new ByteLength({length: 7}));
TypeError: ByteLength is not a constructor
but using byteLength gives a different error, so this

Code: Select all

var byteLength = SerialPort.parsers.byteLength
var parser = port.pipe(new byteLength({length: 8}));
gives

Code: Select all

stream.js:45
  dest.on('drain', ondrain);
       ^

TypeError: dest.on is not a function
    at SerialPort.Stream.pipe (stream.js:45:8)
    at SerialPort.<anonymous> (/usr/local/bin/classes/sensors/btpower.js:14:20)
    at emitNone (events.js:86:13)
    at SerialPort.emit (events.js:185:7)
    at SerialPort.<anonymous> (/usr/lib/node_modules/serialport/lib/serialport.js:188:10)
this seems a better error (i mean, this seems a proper error..) but i have no idea what's wrong with the parser.

any help?

here is my test code, just if you need to kill me :)

Code: Select all

var SerialPort = require("serialport");
var byteLength = SerialPort.parsers.byteLength

var port = new SerialPort("/dev/rfcomm0");

port.on('open', function() {
	console.log('Port open');

	var parser = port.pipe(new byteLength({length: 7}));
	parser.on('data', console.log);


	port.write([0xB4,0xC0,0xA8,0x01,0x01,0x00,0x1E], function(err) {
		if (err) {
			return console.log('Error on write: ', err.message);
		}
		console.log('message written');
	}); 

	port.close(function(err) {
		if (err) {
			return console.log('Error on close: ', err.message);
		}
		console.log('closed');
	}); 
	
});

port.on('close', function() {
	console.log('Port close');
});
port.on('disconnect', function() {
	console.log('Port disconnect');
});

port.on('error', function(err) {
	console.log('Error: ', err.message);
});

Heater
Posts: 9490
Joined: Tue Jul 17, 2012 3:02 pm

Re: Starting to fight with node..

Mon Sep 19, 2016 7:40 pm

Massi,

You have a lot of questions there. Let's see.

1) Yes there are billions of modules. Finding good ones can be an issue. But that's better than not having something that does what you want.

I use "serialport". I do not install it with -g or --unsecure-perms. I almost never install anything with -g, perhaps some development tools like babel. Not things used in my actual programs. Never even heard of --unsecure-perms :) The instructions for installing serialport do not say to use those options https://github.com/EmergingTechnologyAd ... serialport

3) Permissions work the same as any other language.

You have installed node globally. That will have set some path in your user environment to wherever it got installed. When you use sudo you use the environment of the root user so that path is not longer visible to node. Hence it can't find serialport. If you did not use the -g serialport would be installed in node_modules in your project as normal and things would work.

You can try "sudo -E node yourProg.js"

The -E tells sudo to use you users environment variables. This may work or not depending how sudo is configured.

Yep, there is something up with the instructions on the github page. My serialport code looks like this:

Code: Select all

const SerialPort = require('serialport');

const SERIAL_PORT = '/dev/ttyAMA0';
const BAUD_RATE = 115200;
const SERIAL_BUFFER_SIZE = 8;

const port = new SerialPort(SERIAL_PORT, {
    baudRate: BAUD_RATE,
    //parser: SerialPort.parsers.raw
    parser: SerialPort.parsers.byteLength(SERIAL_BUFFER_SIZE)
});

port.on('open', () => {
    console.log('Serial port open');
});

// open errors will be emitted as an error event
port.on('error', (err) => {
    console.log('Serial port error: ', err.message);
})

port.on('data', (data) =>{
    console.log(data);
});
Don't ask me where I got that from. Probably after reading the serialport source code.
And runs like this:

Code: Select all

$ npm install --save serialport
$ sudo node -v
v6.3.1
$ sudo node index.js
Serial port open
.....
Good luck.

Note: I just notice one can also install serialport with -g so as to use the command line tools. Never done that.

Massi
Posts: 1679
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Starting to fight with node..

Mon Sep 19, 2016 8:46 pm

Heater wrote: I use "serialport". I do not install it with -g or --unsecure-perms. I almost never install anything with -g, perhaps some development tools like babel. Not things used in my actual programs. Never even heard of --unsecure-perms :) The instructions for installing serialport do not say to use those options https://github.com/EmergingTechnologyAd ... serialport
Nice, so is it common to install modules "in the project" folder?
if you need to use serialport in a couple of projects, you install it two times?
You have installed node globally. That will have set some path in your user environment to wherever it got installed. When you use sudo you use the environment of the root user so that path is not longer visible to node. Hence it can't find serialport. If you did not use the -g serialport would be installed in node_modules in your project as normal and things would work.

You can try "sudo -E node yourProg.js"

The -E tells sudo to use you users environment variables. This may work or not depending how sudo is configured.
-E works (thanks) but this kills the possibility of using it as a service, since in this case it would be run by root itself.. Well i'll think about installing modules for every project, but this is a strange behaviour to me..
Yep, there is something up with the instructions on the github page.
the parsers syntax is completely different. maybe it's something related to new versions?
Good luck.
this is going to be hard :)
thanks!

Heater
Posts: 9490
Joined: Tue Jul 17, 2012 3:02 pm

Re: Starting to fight with node..

Mon Sep 19, 2016 9:27 pm

massi,

Yes, it is common to install modules in every project. They may all be using different versions of modules and API's change so this can be helpful.

Or you can install modules in some directory, say your home directory, and keep all your node projects in directories under that. node will 'climb' up the directory tree and find them.

I would not use sudo when running code as a service. I just create as systemd service file like so:

Code: Select all

[Unit]
Description= Serial tunnel over websockets.
After=network.target

[Service]
ExecStart=/usr/local/bin/node /home/rsm/serial-tunnel/client.js
WorkingDirectory=/home/rsm/serial-tunnel
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=serial-tunnel
User=root
Group=root
Restart=always

[Install]
WantedBy=multi-user.target
Put that in /etc/systemd/system with an name like "serial-tunnel.service" in this case then use

$ systemctl enable serial-tunnel

to enable it to start at boot up

$ systemctl disable serial-tunnel

To disable running at boot.

$ systemctl start serial-tunnel

To run it at will

$ systemctl stop serial-tunnel

To stop it again.

Note that I use the full path to node in that file to be sure it gets found. Also the full path to the node program. I specify it gets run as root. It gets restarted if it ever crashes out.

The syntax I used is new in Javascript with the ECMA Script 2015 standard, also known as ES6.

It's good to use "const" to indicate an unchanging thing.

"let" has block scope unlike "var". So that is very useful.

The "(x, y) = > {...}" thing is "arrow syntax". It's just a short hand for "function (x, y) {...}".

Did you know Javascript now has classes?

Code: Select all

class point {
    constructor (x, y) {
        this.x = x;
        this.y = y;
    }

    plot () {
        // Draw a point at this.x, this.y
    }
}
Most of the new language features are available in node 6.x.x

It's not so hard. Could be worse, you could be using C or C++ :)

Just ask if you get stuck.

Massi
Posts: 1679
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Starting to fight with node..

Mon Sep 19, 2016 10:01 pm

Heater wrote:Yes, it is common to install modules in every project. They may all be using different versions of modules and API's change so this can be helpful.
nice to hear, thanks for the teaching :) i'll move to this way..
I would not use sudo when running code as a service. I just create as systemd service file like so:
i know, but this will not work with modules installed with "-g", if it depends on user namespace.. am i wrong?
The syntax I used is new in Javascript with the ECMA Script 2015 standard, also known as ES6.
It's good to use "const" to indicate an unchanging thing.
"let" has block scope unlike "var". So that is very useful.
The "(x, y) = > {...}" thing is "arrow syntax". It's just a short hand for "function (x, y) {...}".
i noticed that, good learn :)
Did you know Javascript now has classes?
WOW no i didn't know!
i gave a look to js classes some days ago and found something very different. Good to know..
It's not so hard. Could be worse, you could be using C or C++ :)
Just ask if you get stuck.
i miss my P-starting languages :)
(thanks)

Heater
Posts: 9490
Joined: Tue Jul 17, 2012 3:02 pm

Re: Starting to fight with node..

Mon Sep 19, 2016 11:09 pm

Massi,

As far as I can tell there is no reason one can't install a module twice. Once with

Code: Select all

$ npm install --save serialport
Which gets it into your projects node_modules directory.

And once with

Code: Select all

$ npm install -g serialport
Which puts it wherever, not sure, to be globally available.

The latter is needed in order to use serialports command line tools if I understand correctly. It's needed for things like the babel transpiler if you want to use that from the command line.

Now what is that "--save"

Well. One should start every project with:
$ mkdir funky-project
$ cd funky-project
$ npm init
Answer the questions that npm init asks, mostly just hit return. That will create a package.json file in your project that describes what it is.

Then when you do "npm install --save blabla" it will write that modules name and version into the package.json file.

The magic part of this is that if you give me your code. Without all the node_modules directory, say as a repo on github, then all I need to do is:
$ cd funky-project
$ npm install
And it will install all the modules your project uses.

N.B. I don't think one should put node_modules in git repositories. Others will disagree.

There has always been ways to create classes in JS. You may have seen many tutorials about adding methods to an object or hanging methods off a functions prototype.

I'm not sure the new "class" thing is so brilliant yet. It only seems to be there to make Java programmers feel more at home :)

Now, now, let's not have any talk of those awful "P..." languages here :)

Massi
Posts: 1679
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: Starting to fight with node..

Tue Sep 20, 2016 5:47 pm

hello again :)
i like this sort of "philosophical" thinking about structure :)

so, i should remove the "global" module
Done
then create a folder for my project (as i did with python..)
then all what you said..
Done

Now: the entry point.

In python i have a folder (sensors) of classes (all of my sensors)
when i need them, i can "from sensors import (...)"
how can i have the same in node?
Should i create a project for each sensor?
Or should i make all sensors available together with the entry point script?

thanks a lot Heater :)

Heater
Posts: 9490
Joined: Tue Jul 17, 2012 3:02 pm

Re: Starting to fight with node..

Tue Sep 20, 2016 7:34 pm

Interesting question.

Basically you are saying that you have a bunch of modules, the drivers or whatever, that can be used by one or more programs.

Sounds fair enough.

What you can do is put the modules wherever you like, then in your program specify the path to them when you do "require(my_module)"

For example:

Code: Select all

let express = require('express');
Will look for the "express" module in your node_modules directory. Where "npm install --save express" put it.
(Or some node_modules directory above wherever you are)

But:

Code: Select all

let myModule = require('../my-library/my-module.js');
Will look for "my-module.js" in the "my-library" directory that is one step up the directory tree from your project.

Personally I would not do that. I would put my common code in github or bitbucket or whatever git repository and then include them in my projects with:

Code: Select all

$ npm install --save https://github.com/heater/mymodule
If you are not using git you should think about it. It's so helpful.

But perhaps that is beyond where you want to be just now.

james.arlow
Posts: 1
Joined: Thu May 26, 2016 3:49 am

Re: Starting to fight with node..

Thu Dec 29, 2016 11:09 pm

Found this after banging my head over these same issues. I dug through the serialport module bug tracker, but this was the only mention I could find of the errors I was experiencing.

The reason you are getting the `dest.on` and not a function errors is...

The documentation page is for the unpublished beta (5.x series), whereas the most recent one published to npm is the 4.x series.

The documentation from the series 4 page:...
https://github.com/EmergingTechnologyAd ... md#parsers

You can see that you need to use the constructor parameter to pass the parser, and mentioned in another reply.

This is very bad etiquette on their part, IMHO. I think most node devs are wise enough to keep their beta stuff in a branch until publishing. This is the first time I've been tripped up by a library for this reason.

Fortunately, node can install directly from a git url (no need to manually acquire/install the sources):

Code: Select all

npm install --save git://[email protected]:EmergingTechnologyAdvisors/node-serialport.git
Should be enough to get you running with the current documentation.

ruchivarshney
Posts: 1
Joined: Fri Jan 20, 2017 9:36 am
Contact: Website

Re: Starting to fight with node..

Fri Jan 20, 2017 9:46 am

You have installed node globally. That will have set some path in your user environment to wherever it got installed. When you use sudo you use the environment of the root user so that path is not http://www.printablecalendarworld.net/2 ... e-you.html longer visible to node. Hence it can't find serialport. If you did not use the -g serialport would be installed in node_modules in your project as normal and things would work.
http://www.calendar-holidays.com/2016/07/february-holiday-calendar-2017.html

suji99
Posts: 1
Joined: Fri Feb 17, 2017 10:55 am

Re: Starting to fight with node..

Fri Feb 17, 2017 10:58 am

Will look for "my-module.js" in the "my-library" directory that is one step up the directory tree from your project.

Personally I would not do that. I would put my common code in github or bitbucket or whatever git repository and then include them in my projects. It is my first time i visit here.
http://calendars2016-2017.com/march-201 ... templates/

periodictable
Posts: 1
Joined: Sat Aug 04, 2018 11:54 am
Contact: Website Facebook Google+ Twitter

Re: Starting to fight with node..

Sat Aug 04, 2018 11:58 am

Hello all (hello Heater :))

so i ended up installing node (6.5) just to have something to ask Heater :lol:

installation of node was incredibly simple. Good start.
Then i choose a random thing (in my case: serial port on a rfcomm serial) to test node.
And here starts hell :)
1) node modules are a jungla!! but eventually, i choosed "serialport". This seems ok. I discovered also "strange" params to get npm to work. To install serialport i had to use -g but also "--unsecure-perms". This seems stupid :)

2) an help with code is required, but i'll post later :)

3) how are permissions managed in node?? i mean, look at this:

Heater
Posts: 9490
Joined: Tue Jul 17, 2012 3:02 pm

Re: Starting to fight with node..

Sat Aug 04, 2018 4:14 pm

Well hello periodictable.

1) Yes there are a mind boggling number of node modules out there. I only ever us a handful of the famous ones. Better a jungle than a desert.

I almost never install node modules globally. I like my little projects to keep track of their own modules.

I'm pretty sure you don't need to use --unsafe-perm. I don't recall having to when using serialport.

2) Show us the code.

3) Look at what? Something is missing there.

Return to “Other programming languages”

Who is online

Users browsing this forum: No registered users and 4 guests