si macc
Posts: 1
Joined: Sun Oct 21, 2018 8:42 am

Running Node Js Script as a service

Sun Oct 21, 2018 9:53 am

Hi,

I’m new to programming on a pi and Linux. I’m working on a small project written in node js using the IG trading API via a package I found to install (https://www.npmjs.com/package/node-ig-api).I started on my windows 10 pc which works fine and now transferring to run permanently on my raspberry pi 1 (armV6). Managed to install raspbian and node onto the pi and can run my node js script fine when I set the environment variables required for the program. The next step was to get the script running on boot up and permanently. Tried setting up a service, based on the post here:

viewtopic.php?t=193107

When setting the environment variables and checking they're present by using the printenv command I then run the service I get an error saying:

Error: "value" required in setHeader("X-IG-API-KEY", value)

I inspected the code in the package and traced it back to this code:

Code: Select all

let headers = {
		'Content-Type': 'application/json; charset=UTF-8',
		'Accept': 'application/json; charset=UTF-8',
		'X-IG-API-KEY': process.env.IG_API_KEY
	};
I've got the service running in this folder on the pi:

/etc/systemd/system

With the following script:

Code: Select all

[Unit]
Description=IG Automated Trader

[Service]
WorkingDirectory=/home/pi
ExecStart=/usr/local/bin/node /home/pi/igAutomatedTrader.js
Restart=always
RestartSec=10
#User=nobody
#Group=nobody
#Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production


[Install]
WantedBy=multi-user.target
Then running with the following:

Code: Select all

sudo systemctl daemon-reload
sudo systemctl start igAutomatedTrader
journalctl -u igAutomatedTrader
I'm guessing it must be something in the service script, possibly to do with permissions or an incorrect path but spent a while looking through this forum and stack exchange for an answer but I haven't got the experience or knowledge to know where to look for a solution! Worth noting I also tried to run the js script via pm2 but getting the same error.

Any pointers greatly appreciated, I'm sure it's something simple I'm overlooking.

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

Re: Running Node Js Script as a service

Sun Oct 21, 2018 8:45 pm

si macc,

How about specifying any environment variables you need in the service file. Perhaps like this:

Code: Select all

...
[Service]
Environment="IG_API_KEY=whateveryourapikeyis"
ExecStart=/usr/local/bin/node /home/pi/igAutomatedTrader.js
...
Or, if you environment variables can specified in a file like this:

Code: Select all

...
[Service]
EnvironmentFile=/path/to/some/file/containing/environment/variables.
ExecStart=/usr/local/bin/node /home/pi/igAutomatedTrader.js
...
See here:

https://coreos.com/os/docs/latest/using ... units.html

Return to “Other programming languages”