I have an index.html page which is present at:
D:\GITProjects\codelab\complete\step1\index.html
I am trying to execute D:\GITProjects\codelab\complete\step1\server.js file via node:
"C:\Program Files\nodejs>node.exe D:\GITProjects\codelab\complete\step1\server.js"
Server.js code:
var static = require('node-static');
var http = require('http');
var file = new (static.Server)("D:\GITProjects\codelab\complete\step1");
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(2011);
When I go to hit:
http://localhost:2011/
I see empty page. Any idea why?
The console shows "http://localhost:2011/ Failed to load resource: the server responded with a status of 404 (Not Found)"
You need to keep file.serve(req,res) within req.addListener()
var static = require('node-static');
var http = require('http');
var file = new (static.Server)("./");
var app = http.createServer(function (req, res) {
req.addListener('end',function(){ // <--
file.serve(req, res);
}).resume() // <--
}).listen(2011);
Also, you have a couple of other options to go with(if you dont want to stick with node-static)
Option-1: Use fs module to read the file and send it on request
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(2011);
});
Option-2:
Use a web app framework like express(). It provides several great features to simplify the power of node. Then you can either define a specific route for '/' to send your index.html
var express= require('express')
var app = express()
app.get('/',function(req,res){
res.sendFile('index.html',{ root:__dirname })
})
app.listen(2011)
or serve your static assets straightaway:
var express= require('express')
var app = express()
app.use(express.static(__dirname)); //this will make index.html available to every request
app.listen(2011)
__dirname is the directory that the currently executing script is in. Since both server.js and index.html are at same level, __dirname will point to *D:\GITProjects\codelab\complete\step1*
Related
I followed a tutorial on YouTube that shows how to make a node.js server that works with sockets.
Here is the final working server.js code.
var express = require('express');
var app = express()
var server = app.listen(3000)
app.use(express.static('public'))
console.log('My sockets server is running.');
var socket = require('socket.io')
var io = socket(server)
io.sockets.on('connection', newConnection)
function newConnection(socket) {
console.log('new connection: ', socket.id)
socket.on('send-msg', data => {
console.log('send-msg');
socket.broadcast.emit('send-msg', data)
})
}
This code works when I host it on my local server (http://localhost:3000/). Now I am trying to get it to be online using cPanel, I got the libraries set up correctly (I think) and I am using the same code, but it's not working. I'm just getting Cannot GET /mychat poping up in the display.
I tried making some changes:
...
const hostname = '[the ip address of my server]';
const port = 3000; // also tried port 22, same issue
var app = express()
var server = app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
...
But I get the same issue.
When cPanel first created the server.js file, it made this code:
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
which does it's job, but it doesn't help me.
Here is the basic structure of the site:
root
- package.json
- package-lock.json
- server.js
> node_modules (folder with all of the required files including express and socket)
> public
- index.html
- script.js
- styles.css
You have to define the path and the directory, so the server can receive and send an Httpresponce. For the main directory it would be:
app.get('/' (req, res) => {
res.send('Home page')
});
In this case the main directory is just '/' and the server gets a request, whenever a client goes to the url and then it responds, in this case with a text document, 'Home page'.
Im trying to display a html file from my node app. Heres my code:
var http = require('http');
var fs = require ('fs');
var path = require("path");
var filePath = path.normalize('/NodeJS/projects/test.html');
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type' : 'text/html'});
var myReadStream = fs.createReadStream(filePath);
myReadStream.pipe(res);
});
server.listen(3000, '127.0.0.1');
console.log('listening to port 3000');
I ran into the same problem earlier trying it with __dirname but It didnt work so I wanted to try using path.normalize.
Any pointers as to why this is not working. If I copy the dir from the console error into my explorer my test.html file opens.... The file is there. This must be some simple error but its killing me
I think this can be done in a simpler way.
I have my file in root folder
The path.normalize() method normalizes the given path, resolving .. and . segments.
path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf
var http = require('http'),
fs = require('fs');
var path = require("path");
var filePath = path.normalize('./index.html');
console.log(filePath)
//here you can include your HTML file
fs.readFile(filePath, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(3000);
});
I'm trying to call a socket.on() event from an external .js file and I can't figure out what I'm missing...
I'm using NodeJS with ExpressJS.Below are the files:
app.js(the server file)
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
var io = require('socket.io')(http);
....
//Socket Io functions
const ioObj = require( './library/io.js')(app, express, io);
// This route will be used to print the type of HTTP request the particular Route is referring to
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
....
/library/io.js (sockets file)
module.exports = function(app, express, io){
io.on('connection', async function(socket) {
socket.on('refreshPage', function(){
console.log("page should now be refreshed !!");
socket.emit("refreshPageNow");
});
....
});
}
What I'm trying to do is to call/access the refreshPage event from /library/io.js so I can send further a "refresh webpage" signal.
I tried to do something like :
io.sockets.emit("refreshPage");
and
ioObj.sockets.emit("refreshPage");
But didn't work...
actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.
here is the code :
var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
To send a single file for a specific route use the res.sendFile() function.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});
app.listen(3000);
In case you want to serve all files in a directory use the express.static() middleware
var express = require('express');
var app = express();
app.use(express.static('path/to/my/directory'));
app.listen(3000);
With express u can do something like
//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
app.use(express.static("./file"));
})
server.listen(8000);
I have a Problem with my Node.js Server. I want to host a html Document but there is one Problem with a TypeError. I cann't find the mistake. Can you help me?
var express = require("express");
var mysql = require('mysql');
var app = express();
var fs = require("fs");
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : '',
database : 'test',
debug : false
});
app.get('/', function(req, res) {
fs.readFile('index.html', 'utf-8',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
app.listen(3000);
console.log("SERVER IS NOW RUNNING AT PORT 3000........");
Here now the log:
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.2\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" Server.js
SERVER IS NOW RUNNING AT PORT 3000........
_http_outgoing.js:430
throw new TypeError('first argument must be a string or Buffer');
^
TypeError: first argument must be a string or Buffer
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:430:11)
at ReadFileContext.callback (c:\........\Server.js:21:13)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:303:13)
Later I want to make a MySQL Connection with Pooling.
You can also use createReadStream and .pipe to res but as #robertklep mentioned, you should check if (err) inside the readFile callback.
Here is the example
var fs = require('fs');
var http = require('http');
var file = fs.createReadStream('/path/to/file');
var server = http.createServer(function (req, res) {
// res.writeHead(200, {
// 'content-type': 'text/plain'
// });
file.pipe(res);
});
server.listen('3000');
UPDATE
So to match your code using express, you don't have to do much:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {
console.log('SERVER IS NOW RUNNING AT PORT 3000........');
});
Just put all your assets in the public folder and you should be good to go. To find more info about Express you can go to http://expressjs.com/en/4x/api.html