Running file from ssh connection doesn't work correctly. File got executed correctly only with direct connection

This topic is confusing, I know. I can't really say what my problem is about. In few words I'll explain whats going on - I've got a AWS (amazon web service) where I've got node.js with script that looks like that:

#!/usr/bin/env node
var fs = require('fs');
var outfile = "slogan.txt";
var text = "A startup is a business built to grow rapidly.\n";
fs.writeFileSync(outfile,text);
console.log("Script: " + __filename + "\nWrote: " + text + "To: " + outfile);

pretty simple, right? Cool! I want to execute it from my computer so i'm doing it like that

ssh host1 node week2/part1.js

where host1 is working properly in 100% and its connection with .pem between MAC and AWS. Script got executed:

Bitmakers-iMac:~ Bitmaker$ ssh host1 node week2/part1.js
Script: /home/ubuntu/week2/part1.js
Wrote: A startup is a business built to grow rapidly.
To: slogan.txt

but... there is no slogan.txt! I have to get conenction inside server

ssh host1 

and then run it form server. Can anyone can explain me why its working like that? I udnerstand its may still be confusing but I hope this screenshot will help a bit in understanding this. Thanks for reading this long post! I hope you know the answer. enter image description here

There is a basic difference in the way you execute the command over ssh and from within the shell.

From within the shell, you say cd week2 and then issue node part1.js whereas you say ssh host1 node week2/part1.js in the other case. The file slogan.txt is located inside the directory containing part1.js and cannot be located when you say node week2/part1.js.

Change the following line

var outfile = "slogan.txt";

to specify the complete path to slogan.txt instead.

You'll be able to reproduce the problem if you try

cd ~ && node week2/part1.js

from the shell.

When you ssh to the server the first thing shell does is read all the environment files (.profile, .bashrc, .kshrc, etc...). When executing remote command, however, this will not happen. Try sourcing required env file before executing, for example:

ssh host ". ./.profile; node week2/part1.js"

Might also need to use . ./.profile; . ./.bashrc; or . ./.profile; . ./.kshrc;, depending on what shell you use and if those files have env (mostly PATH) settings too.