This question already has answers here:
What is the best practice for serving html in node.js with express.js?
(2 answers)
Closed 5 years ago.
I'd like to implement a chatroom by node.js.
I use the template provided by socket.io.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
app.get('/', function(req, res) {
fs.readFile(__dirname + '/style.css'); // I don't know how to import the style.css to the chat.html
// fs.readFile(__dirname + '/images/'); // And how to add images file to the server
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
})
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.broadcast.emit('hi');
});
http.listen(8888, function() {
console.log('listening on *:8888');
});
When I type
node index.js
in the terminal, it'll show up
listening on *:8888
(node:12873) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
Now, the server can work but the format is gone.
I don't know how to correct this. I hope that the chat.html can be in the format specified by the style.css and the messages can be sent in the format(also specified by the style.css) I desired not just pure text.
You have to tell node the directory that you plan to use for "Static files".
You do it like so
const staticCont = express.static(__dirname + "/public");
Where "public" is the name of the folder that will hold your static content like CSS or front end JS files etc.
hope this helps
Related
I am trying to display filesize on with socket.io with every time file changes. Here is my js code.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
var fs = require("fs");
var filesize;
var filename = 'D:\\test.txt';
fs.watchFile(filename, function() {
fs.open(filename, 'r', function(err, fd) {
fs.stat(filename, function(err, stat) {
if(err) { console.log('error'); }
console.log(stat.size);
filesize = stat.size;
});
})
});
io.on('connection', function(socket){
console.log('A user connected');
socket.emit('testerEvent', { description: prntarr});
socket.on('clientEvent', function(data){
console.log(data);
});
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
The problem is , socket is not refreshing data but console shows changed size. It refreshes only when i reload the page. Please suggest where i am making mistake and how to fix it.
thanks in advance.
You need to do a socket.emit() inside your fs.watchFile() callback. You're not emitting anything when the file changes at the moment
When a user connects, push his socket in an Array.
Inside the watchFile callback, iterate through the connected sockets Array and .emit() what you want to send.
Don't forget to remove from that
Array any sockets that have disconnected
I have a hard time understanding when server "send" the data and when client "get" the data and vice versa.
The code is in their example
in index.js for nodejs
// server side
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
// create chat message
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log('message: ' + msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and in the script
$( function(){
'use strict';
// client side
console.log("starting chat...");
var socket = io();
$('form').submit(function(){
// call event chat message
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
// create chat message event on client
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
})
});
as you can see on index.js it create a chat message and using io it emmit it. The same thing is on in the script. So the question is how does the server and client "talk" with each other? and what it is the different between emmit and on ?
Whenever we are using socket io , we use emit to send server a message with given message identifier and server now replies client by emitting a message with some message identifier say x, then we use that on method and pass x identifier and grab the message from server.
I would like to try out node orm2, with sqlite. I tried the example code, and changed mysql to sqlite. It looks like this:
var orm = require("orm");
orm.connect('sqlite://D:/orm_test/database.db', function (err, db) {
// ...
});
I don't get any error, or warning. Just nothing happens. The callback is not called at all.
It does not work, even if I create database.db before
According to the documentation the callback is only called when the connection is done successfully (or unsuccessfully)...
So if your path is incorrect (for any reason, and your connection is NOT explicitly unsuccessfull), maybe there is no callback ?
You can avoid callback if you listen for the connect event directly as this :
var orm = require('orm');
var db = orm.connect('sqlite://D:/orm_test/database.db');
db.on('connect', function(err) {
if (err) return console.error('Connection error: ' + err);
// doSomething()...
});
The connection URL is like :
driver://username:password#hostname/database?option=value
You can use the debug option to prints queries into the console, maybe there will be more informations ?
EDIT :
Well, I just tried to use it and did that :
// REQUIRES
var express = require('express');
var app = express();
var orm = require("orm");
var sqlite3 = require('sqlite3');
// SERVER CONFIGURATION
var port = 5050;
// APP CONFIGURATION
app.use(express.static('public'));
app.use('/static', express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
// ROUTES
app.get('/', function(req, res){
orm.connect('sqlite://C:/Users/Me/Documents/Projects/test/database.db', function(err, db){
console.log('connected to this db : ' + JSON.stringify(db));
});
});
app.listen(port, function(){
console.info('Server successfully started, listening on port ' + port);
});
And it works... JSON.stringify shows what is the content of DB Object in the console.
Does your code looks like this ?
How do I make a server that has a socket connecting to one client(Client A) also have a socket to another server? Basically how do I have the server become a client as well(to another server)?
If the answer is to load the socket.io-client then how would I do that in a javascript file?
var app = require('express')();
var http = require('http').Server(app);
var http2 = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("asdf");
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3050, function(){
console.log('listening on *:3050');
});
http2.listen(1337, function(){
console.log('listening on *:1330');
});
var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){
console.log('connected');
});
I assume you mean that you want to run a node server as a client since you mention javascript file. Here is how to set up a socket client in node. Get the package npm i socket.io-client. Then use it in node as shown below.
var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){
console.log('connected')
});
I really hope to find some answers here as i tried everything by now.
Background:
Overtime we deploy code to web server, we need to do a cache warm up, i.e. access the site and make sure it loads. First load is always the slowest since IIS require to do some manipulations with a new code and cache it.
Task:
Create a page which will a checkbox and a button. Once button is pressed, array of links sent to server. Server visits each link and provides a feedback on time it took to load each page to the user.
Solution:
I am using node JS & express JS on server side. So far i manage to POST array to the server with links, but since i have limited experience with node JS, i can not figure out server side code to work.
Here is a code i got so far (it is bits and pieces, but it gives an idea of my progress). Any help will be greatly appreciated!!!
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false});
var http = require("http");
function siteToPrime(url){
http.get(url, function (http_res) {
// initialize the container for our data
var data = "";
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log(data);
});
});
};
//Tells express where to look for static content
app.use(express.static('public'));
app.post('/', parseUrlencoded, function(request, response){
var newBlock = request.body;
console.log(Object.keys(newBlock).length);
var key = Object.keys(newBlock)[0];
console.log(newBlock[key]);
siteToPrime("www.google.com");
response.status(201);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});
Assuming that you have access to the array in the post route:
var express = require("express"),
request = require("request"),
app = express();
var start = new Date();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
function siteToPrime(req, res, urls) {
urls.forEach(function(url)) {
request(url, function(error, res, body) {
if (!error && res.statusCode == 200) {
console.log(url +' : ' + body);
console.log('Request took: ', new Date() - start, 'ms');
}
});
}
res.redirect('/');
};
app.post('/', function(req, res){
var urls = req.body.urls // Array os urls.
siteToPrime(req, res, urls);
});
app.listen(3000, function(){
console.log("Server listening on port 3000...");
});