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
Related
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);
});
im writing a webserver in nodeJs as seen in the following code. I got the server working but sadly i cant acces the website outside my network (localhost). How can i do this?
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(80, function(){
console.log('Server running on 80...');
});
I also used this method to check if the other method was the problem.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('Index.html', function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
}).listen(80);
Have you tried binding the port externally ?
connect().use(serveStatic(__dirname)).listen({
host: '0.0.0.0',
port: 80
}, function(){
console.log('Server running on 80...');
});
I have a node js app with the npm mssql module. I have purchased a cloud Windows 2012 server and when trying to call the stored procedure, it throws the error.
Throws error at ps.prepare("exec usp_Get_Cars #param", function(err)
var express = require('express');
var app = express();
var router = express.Router();
var util = require('util');
var recieve = require('./recieve');
var userID = "7DF506E1-700D-4D30-8162-74A903743561";
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use('/style', express.static(__dirname + '/style'));
app.use('/script', express.static(__dirname + '/script'));
var sql = require('mssql');
var config = {
user: 'prod_admin',
password: 'myPassword',
server: 'serverName',
database: 'elements'
};
app.get("/getCars/:userID", function(req, res) {
var userID = req.params.userID;
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
ps.input('param', sql.NVarChar(sql.MAX));
ps.prepare("exec usp_Get_Cars #param", function(err) {
ps.execute({
param: userID
}, function(err, recordset) {
console.log('Recordset: ' + JSON.stringify(recordset));
res.send(recordset);
ps.unprepare(function(err) {
console.log('Error on unprepare: ' + err);
});
});
});
});
});
app.get('/', function(req, res) {
res.sendFile('home.html', {
'root': __dirname + '/templates'
});
});
app.listen(3000, function() {
console.log('Node server running # http://localhost:3000');
});
I did try searching for why this error occurs, but can't find anything relating to mssql or node. You can see the code that throws the error here. I am wondering if this is an issue with the server setup?
There are no errors in the js file and I have no issues running this on my Windows 10 local machine. Any ideas?
It was a firewall issue with AWS. I was unable to determine how to fix it through Amazon. But I moved my database to another server and it worked.
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 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*