How to execute a Node.js script on the server? - javascript

I'm beginning to learn web technologies and programming and I'm setting up my own local webserver. I have HTTPD, PHP, Python, MySQL all up and running on Windows. Now I want to add Node.js to the mix. I installed the Windows 64 bit installer. Now how do I begin? I have a basic Hello World script in a test.js file. But when I access this file in the browser it only displays as plain text. It's not executed. How to execute a Node.js script on the server?

Starting a node script is pretty simple. Just use your command line or terminal and execute the following command.
node /path/to/your/file.js
Doing so you'll start your node script. If you're going to start a server it's pretty much the same. Just keep in mind to define a server in your node file and start it. A simple server using express could look like this (You can also use a fully node way, this is just a simple example using express. You may check google for how to set up a simple node http server).
var express = require('express');
var app = express();
var port = 4000;
app.listen(process.env.port || port);
As you can see the specified port is set to 4000. You can simply adjust this by changing the value itself or passing in a node environment variable. To pass in an environment variable just start your server like this.
node port=3000 /path/to/your/file.js
This will finally pass the value of port to process.env.port which obviously will start your server on the port 3000.

you can use these packages to keep the file running so you won't have to login to server every time :-
forever
and you can just write :-
forever start app.js
nodemon
nodemon app.js
pm2
which is very useful , as it will auto restart your app when it crash or any error happens
pm2 start app.js

Your run your file: node server.js
Then it starts.
There should be specified in code on which port you run your server. Then it is accessible for example at http://localhost:3000/
As Quentin noted, I was thinking about "creating web server". Of course, you can run javascript code with Node.js without server. Then skip the part abot localhost, just use node test.js in console.

Related

Moving ExpressJS API files onto Server

So I created an simple API using ExpressJS that connects to MongoDB to perform CRUD operations. Currently I am able to get the local host running by performing command "npm nodemon" in the source folder. And it worked by testing with postman I wonder how to implement it on the server. As server runs a linux system, also I have a line of code in my root file "server.js ":
const port = process.env.PORT || 5000;
I think the process.env.port needs need to be changed in order to make it work on the server?
In addition, I did look into aws CE2 server it is so complicated that I was immediately overwhelmed. I am hoping someone can recommend dummy like me a simple and very specific solution to have a server run my scripts in ExpressJS environment. Thank you
I'm assuming your question is "How to deploy express app to a server?"
You can read some advanced topics on http://expressjs.com/, which covers some best practices, and other useful stuff. But the things you want to look at now is Things to do in your environment / setup
The important part is:
Keep your express runing on port 5000
Run your app in cluster
Run your app behind a proxy server like Nginx.
You can check this nice guide (Step 3 and 4) on how to deploy your express app to a Linux server with PM2, Nginx.
So at the end, your express app will run on port 5000 (or whatever port you desire), and your Nginx will run on port 80, and nginx will forward any request to your express app.

deploying node add on server without using localhost

I have a node app that I am trying to deploy on my server. I have an index.html file in a public folder and an app.js file. If I navigate to the project in the command line and run node app.js it runs the app on localhost:8888 and shows the index.html file.
Now that I have uploaded this to my server I am wondering what I need to do, and change (if anything) in my app.js file so that i can visit the site without visiting localhost:8888, but instead the actual url.
I have tried http://162.xx.xxx.xxx/folderName/app/public:8888, but this doesn't work.
var express = require('express')
var app = express();
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(8888, function () {
console.log('Example app listening on port 8888!')
});
"Server" is a word with two primary meanings in software development.
It can mean either "A piece of software that listens on a network" or "A computer running that kind of software".
So having uploaded the JavaScript program to the remote computer that is your server you need to do exactly the same as you did on your own computer.
i.e. you need to get a terminal on the server and run node app.js
It will then be available at http://your.example.com:8888/
(More advanced uses would involve using software like forever or system.d to run it automatically as a background process).
If you were using the term server with the other meaning (i.e. you mean "Apache HTTP" or "IIS" or similar), then you are out of luck.
Using Node for server side code means running a server written in JavaScript.
To use this in combination with something like Apache, you would either:
Run the Node server instead of Apache
Run the Node server on a different port and point some services at that port explicitly
Run the Node server on a different port and use something like ProxyPass to have Apache relay requests to it
Change the port number from 8888 to 80 and then use the address of your server in the browser. For example, "mysite.com" for a domain name or "123.45.678" for an IP address.
If there are other sites on that server, you can't run it on port 80. (Port 80 is the default port websites use.) You'd need to use a different port. So, say you kept 8888 -- the address would be yoursite.com:8888

Web console for docker container

Situation
There is a data-only-container named: app-data
There is a copier container worker
Initially app/data was created and that's it, it's status is 'stop' / exited.
Then the copier worker copies some files to app/data as its volume, for example an server.py
Okay this was done like this:
docker run --rm --volumes-from app-data /somelocation/server.py ~/www/
the copier takes 2 arguments, the file to copy and where to copy
With that at hand, I can run a image named app/serve to server the file in the volume like so:
docker run --volumes-from app-data -d -P app/serve
the image entry point do this http-server, and workdir is same as the data volume, so it'll run
Hell yeah it works, and the python web app can be accessed in the host with a highport like so: 0.0.0.0:49124 because
the app/serve image expose ports 5000 which is used by the sever.py script
I had the above working, you can focus below.
So the app can run huh? But I want to do more complex things that just running the app (I ran the app using the remote api), what if I want to run the app using a web console connected to a docker container.
My Idea of how would it be possible
use term.js
expose 2 ports e.g. (4000, 5000)
use port 4000, so that when term.js executes in port 4000, it'll generate a highport for the client to use in the web console socket connection
use port 5000 to allow whatever web application ran in port 5000 will be available in a another highport, to be accessed like so 0.0.0.0:49124
This is a prototype implementation of how runnable/dockworker do this, I am still new to nodejs that is why I cannot comprehend how they do it, could there be a less-featured simpler execution of this idea?

Automate UI testing with Javascript, node - starting & stopping a web server

I'm currently investiagating automated UI testing using JavaScript on windows with node.js and phantom.js and unsurprisingly I've found many frameworks that can help in this regard (casper.js, Buster.js, etc).
The one thing that seems to be missing from the frameworks I have looked at so far is stopping and starting a web server to server the web pages so that testing framework can perform its testing. One exception is WebDriver.js which uses the Selenium standalone server but this relies on a server written Java and at the moment I'd prefer to find a node based solution if at all possible.
From the node perscpective I've looked at Connect.js and also Http-Server (which I particularly like) but the issue is starting and stopping these from a JavaScript test.
I've attempted to create a casper.js test that would interact with a server, run the test and then stop the server but I can't get it to work, here's an example script
var childProcess = require('child_process').spawn('http-server', '/TestSite');
casper.test.begin("Load-page", 1, function suite(test){
casper.start('http://localhost:8080/',function(){
test.assertTitle("test page");
});
casper.run(function(){
test.done();
childProcess.kill();
});
});
I call this from the command line using the following command (casper is in my Path variable):
casperjs Load-page testFile.js
What I was hoping would happen is the http-server would start, casper would start the test and then after the test was run the http-server would be killed.
I've also tried similar with Connect:
var server= connect.createServer(connect.static('/TestSite')).listen(8080)
casper.test.begin("Load-page", 1, function suite(test){
casper.start('http://localhost:8080/',function(){
test.assertTitle("test page");
});
casper.run(function(){
test.done();
server.stop();
});
});
But again with no luck.
I can run the Casper sample tests which work and I've also got Node in my Path as well and can call the REPL from the command prompt.
The directory structure is:
Code
/TestSite
/node_modules
and I run the tests from the Code folder.
Am I simply unable to do this or am I just not getting how it should work?
When you say "no luck" what do you mean?
The connect example looks mostly OK, and I'd prefer it over spawning a subprocess. Bear in mind that listen is potentially async so the server might not be available immediately though. The second param to listen is a callback that will be run once the server is listening - maybe try running the tests in that callback instead?
Pro Tip: Don't rely on port 8080 always being free on whatever machine you're running on - passing in 0 for the port will cause the server to start on a random port, you can then do server.address().port in the listen callback to get the port that was chosen
I managed to get it working using a combination of differebt scripts and using child_process spawn.
I created a script called startServer.js that would start the server using Connect:
var connect = require('connect');
var server= connect.createServer(connect.static('TestSite'));
server.listen(8081);
I created another script runTests.js that would call the server script via spawn and then call Casper, again via spawn, and run all the capser tests that are in a folder called tests relative to where the script is run from.
var child_process = require('child_process');
var stillRunning = true;
var server = child_process.spawn('node', ['createServer.js']);
var casper = child_process.spawn('casperjs', ['test tests']);
casper.stdout.on('data', function(data){
console.log(data.toString());
});
casper.stderr.on('data', function(data){
console.log('Error: ' + data);
});
casper.on('exit', function(code){
server.kill();
process.exit(0);
});
To use this at the command prompt navigate to the folder where the script is and then run node runTests.js and the server will be started and the tests run against the site

OpenShift NodeJS deployment : socket.io index.html port assignment, etc

I locally wrote a nodeJS app using socket.io and express modules.
I wanted to use openshift for hosting.
So I changed the main .js to server.js which seems to be the index equivalent of the openshift file and changed the server port setting to:
var server = require('http').createServer(app).listen(process.env.OPENSHIFT_NODEJS_PORT || 3000);
as indicated in some posts.
However after git commit, I am still getting:
remote: info: socket.io started
remote: warn: error raised: Error: listen EACCES
remote: DEBUG: Program node server.js exited with code 0
remote:
remote: DEBUG: Starting child process with 'node server.js'
and the website doesn't work.
As the app is serving a html file, there are two more places, where the port is mentioned, which sit in the index.html that is served:
header:
<script src='//localhost:3000/socket.io/socket.io.js'></script>
and within javascript for the html file:
var socket = io.connect('//localhost:'+process.env.OPENSHIFT_NODEJS_PORT || 3000);
// intial vars and multi list from server
socket.on('clientConfig', onClientConfig);
All files and modules are seemingly uploaded, but the EACCES error still prevails.
I get the feeling that maybe the header link to localhost:3000 might be the skipping point, but I am not sure. Anyone have any idea, what the problem is?
Also, there is no : socket.io/socket.io.js file in the socket.io modules folder, which I find confusing.
I had recently developed a chat client application using socket.io and also had webrtc in it. I was able to deploy the app on openshift by making the following changes into code.
Client Side
Keep the include script tag in a relative manner like so
<script src="/socket.io/socket.io.js"></script>
While declaring io.connection, change the ip part to point the application to server in this format.
var socket = io.connect('http://yourapp-domain.rhcloud.com:8000/', {'forceNew':true });
8000 is for http and 8443 is for https
Server Side
The io and the server should both be listening on the same port and the order in which the statements are run should also be given attention.
Step 1: Declare the http server using app.
( app is obtained from express)
var express = require('express');var app = express();)
var server = require('http').Server(app);
Step 2:
Declare io from socket.io and combine it with the server object.
var io = require('socket.io').listen(server);
Step 3:
Now, allow the server to listen to openshift port and ip.
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
Please pay special attention to the order of the statements you write, it is the order which causes issues.
The server side of your websocket needs to listen on port 8080 on your openshift ip address, the CLIENT side needs to connect to your ws://app-domain.rhcloud.com:8000
I have a few notes on how to use WebSockets here: https://www.openshift.com/blogs/10-reasons-openshift-is-the-best-place-to-host-your-nodejs-app#websockets
You don't need any additional server-side changes after adapting your code to take advantage of environment variables (when available)
OpenShift's routing layer exposes your application on several externally-accessible ports: 80, 443, 8000, 8443.
Ports 8000 and 8443 are both capable of handling websocket connection upgrades. We're hoping to add support for WebSocket connections over ports 80 and 443 soon.

Categories