How to run node on server - node.js

i am new in node.js and i want to create chat system so anybody help me that how can i run my codes on local and on server
Server - (app.js):
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
Client - (index.html):
<script>
var socket = io('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
what is server (app.js) and how can i run this on my server and how can i call this function to client ?

Step 1. Install node.
Download package from https://nodejs.org/en/, then you got npm and node file.
Create soft link to /usr/local/ for npm and node file.
Step 2. Crate your app.js, and typing:
node app.js
then, your code is running. And you can test in your frontend.
If you wanna your code running background, you can use pm2.
npm install -g pm2
After that, pm2 start app.js. Your code is running background.

See https://www.tutorialspoint.com/socket.io/socket.io_hello_world.htm
You need node installed on your server as a prerequisite.
Once you have nodejs installed, the app can be executed as node app.js

Related

WebSQL access in Electron application

I have an Electron application running a Node Express server. The Electron main process is:
var express = require('express');
var app = express();
app.get('/', function() {
/* I want to use WebSQL here */
res.send('Hi !!!');
});
app.listen(3636, function() {
console.log('Listen ...');
});
var window = new BrowserWindow();
window.loadURL('http://localhost:3636');
I want to use WebSQL inside my Node Express controllers but, i tried with openDatabase command and obviouslly i received "undefined function" error.
Any ideas ?
The reason you get undefined function is that you're trying openDatabase in node and not in the browser. If you still really want to use websql but in node you can try out https://github.com/nolanlawson/node-websql#readme (npm install websql -S to add it to your package.json)

Automate Functional Testing in node.js

I checked some NPM libraries to test a webpages or web-services. But all of them expect that the server is already running. Since I want to automate functional testing, how can I setup NPM package in such a way that
It can start the server
Test the application
Stop the server
So that I can test it locally, as well as on online CI tools like travis-ci or circleci.
Case 1: Webservice
I wrote a NPM package which starts nodejs HTTP(s) server. It can be started from command line $stubmatic. Currently, I use 2 approaches to test it,
manual : I manually start it from command line. Then run the tests.
Automatic: I use exec module to run a unix command which can start the application and run pkill command to kill the application. But for this automation, my application need to be installed on testing machine.
Case 2: Website
I have create a NPM package: fast-xml-parser and created a demo page within the repo so that I can be tested in the browser. To test the demo page, I currently start a local server using http-server npm package manually. Test the application.
What can be the better way to write automate functional tests for node js applications?
Note:
I never used task runners like gulp or grunt. So I'm not sure if they can help in this case.
In case 1, my application starts node js native HTTP server. I'm not using any 3rd party application like express currently.
This question mentions a new Docker container system for Travis that could be duplicated locally. It might be a way: How to run travis-ci locally
Did you look at supertest (SuperAgent driven library for testing HTTP servers) and expect (Assertions library)(documented here) with mocha (Test Framework)?
I use them and I never had any kind of problems for all the tests I do until now.
The documention in the links contains all the informations you need to build up your test.
Case 1: Webservice
Problem 1
As nodejs server.close() was not working. I copied paste this snippet in every test file which is starting my webservice.
try{
server.setup(options);
server.start();
}catch(err){
console.log(err);
}
Once all the tests are completed, server stops.
**Problem 2
I was using chai-http incorrectly. Here is the complete working solution.
//Need to be placed before importing chai and chai-http
if (!global.Promise) {
global.Promise = require('q');
}
var server = require('.././lib/server');
var chai = require('chai')
, chaiHttp = require('chai-http');
chai.use(chaiHttp);
try{
server.setup(someoptions);
server.start();
}catch(err){
console.log(err);
}
describe('FT', function () {
describe('scenario::', function () {
it('responds to POST', function (done) {
chai.request("http://localhost:9999")
.post('/someurl')
.then(res => {
expect(res.status).toBe(200);
//console.log(res.text);
done();
}).catch( err => {
console.log(err);
done();
});
});
});
Case 2: Website This was quite simple.
I used http-server to start the server so my html files can be accessed.
I used zombie js for browser testing. (There are many other options available for browser testing)
Here is the code
process.env.NODE_ENV = 'test';
const Browser = require('zombie');
const httpServer = require('http-server');
describe("DemoApp", function() {
var browser = new Browser({site: 'http://localhost:8080'});
var server = httpServer.createServer();
server.listen(8080);
beforeEach(function(done){
browser.visit('/', done);
});
describe("Parse XML", function() {
it("should parse xml to json", function(done) {
browser.pressButton('#submit');
browser.assert.text('#result', 'some result text');
done();
});
});
afterEach(function(){
server.close();
})
});

Include Node.JS + Socket.IO in Symfony2 application

I have done many researches and it seems I can't find the proper solution. I am confident in PHP. I also have done some tutorials on Node.JS and Socket.IO and I'm currently learning Symfony2 but I can't see how I can merge the two to achieve my goal.
My goal is to set up real-time notification for back-end users of my app. This app is a e-commerce website and I want the admin behind the scenes to be warned as soon as an order is made by a visual notification in the upper right corner of the admin panel. My server use FreeBSD.
My plan is to use Node.JS and Socket.IO to achieve this. If there is a better plan, I'm willing to hear about it. Otherwise, I cannot find proper resources to tell me how I can include Node.JS and Socket.IO to a Symfony2 app. I use composer to install bundles but I haven't used NPM with Symfony2.
I have found this question, this link and this other question to help me out but none of these tell me how I can install Node.JS in a Symfony2 app.
If someone could help me with the steps to complete to make me start developping this feature, I'd be glad.
Thanks!
For those who might be interested in the answer:
$ su -
Install Node.JS
$ cd /usr/ports/www/node
$ make install clean
Install NPM
$ cd /usr/ports/www/npm
$ make install clean
Install Socket.IO
$ cd /path/to/your/project/js/public/files
$ npm install socket.io
Develop the code
app.js
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('newOrder', function () {
socket.broadcast.emit('message', 'Nouvelle commande');
});
});
server.listen(4321);
Front-end
<script src="{{ asset('http://localhost:4321/socket.io/socket.io.js') }}"></script>
<script>
jQuery(function($) {
var socket = io.connect('http://localhost:4321');
$('form').on('submit', function() {
socket.emit('newOrder', '1');
});
});
</script>
Back-End
<script>
jQuery(function($) {
var socket = io.connect('http://localhost:4321');
socket.on('message', function(message) {
alert(message);
});
});
</script>
Launch server
$ node app.js
That's all!

Node.js Server Start and Stop

I am starting to learn Node.js and one of the annoying things I am encountering is the starting and stopping of the server when I make a small change to the .js file. Any alternatives?
You can try installing
npm install -g nodemon
And then you run your server
nodemon server.js localhost 8080
That automatically makes you restart the server every time you save new changes
More Info. Nodemon
Use something that watches for file changes and automatically restarts node. nodemon is a good choice.
$ sudo npm install -g nodemon
$ nodemon app.js
server.close
Do not call close before the "listening" event fires.
Either add a callback to listen or add an event manually
server.listen(port, host, function () { server.close(); });
// OR
server.on("listening", function () { server.close(); });
server.listen(port, host);
var net = require('net');
var server = net.createServer(function(socket) {
socket.on('data', console.log);
server.close();
});
server.listen(32323);
var socket = net.createConnection(32323);
// call end to make sure the socket closes
socket.end('hi');
There are nice pre-build modules that can do this for you. Check out nodemon, for example -- install it with npm: npm install -g nodemon
Instead of running node app.js you run nodemon app.js; it will automatically restart your application whenever you make a change.

socket.io keeps 404ing?

sorry for the silly question and im sure its a noob mistake. I am following the how to use for socket io: http://socket.io/#how-to-use and keep having an problem;
I have a node app (running version 3.0 alpha of express) and have the following:
app = express()
io = require('socket.io').listen app
I have edited the layout.jade and added:
script(src="/socket.io/socket.io.js")
I have also run npm install socket.io and confirmed that it starts fine on the server.
If I browse to any page, console keeps showing:
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)
Anyone else experienced this issue?
Here are step by step instructions I just tested them
express socket
cd socket
npm install
npm install socket.io
Add the following in app.js
var io = require('socket.io').listen(app);
Run
node app
In the console you should see
info - socket.io started
In the browser go to
http://localhost:3000/socket.io/socket.io.js
You should see the raw JavaScript
Edit:
I'm also having problems with 3.0alpha1. Looks like a bug. Here is an ugly work around
var fs = require('fs');
app.get('/socket.io/socket.io.js', function(req, res) {
fs.readFile('/PROJECT_HOME/node_modules/socket.io/lib/socket.io.js', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
}
});
});
Are you runnning layout.jade from the app.js?
app.get('/',function(req,res){
res.sendfile('index.html');
});
This needs to be included in the app.js assuming your template is in index.html file.

Resources