I am not able to add CSS files in node JS - node.js

I am not able to add css and js file please give me a code by which i can use my css or other files
This is my code:
const http = require('http');
const fs = require('fs');
const port = 3000;
fs.readFile('index.html',(err,html) => {
if(err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('content-type', 'text/html');
res.write(html);
res.end();
});
server.listen(port, hostname, () =>{
console.log("server started on port: "+port)
});
});
my file location is
test.js
index.html
public /css==>here my css files
/js ==>here my other js files

Related

Vanilla Node js Server, Css not loaded [duplicate]

This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 10 months ago.
I am trying to write a web server application for my Frontend.
The structure is for the fronted files is :
Backend
server.js
Fronted
Index
Javascript
index.js
style.css
index.html (it is outside of Frontend folder)
The code for server.js is:
const fs = require('fs');
const port = 5000;
const server = http.createServer(function (request, response) {
fs.readFile('../Frontend/index.html', function (error, data) {
response.setHeader( "Content-Type", "text/html");
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
} else {
response.write(data);
}
response.end();
})
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});
When I try to access localhost:5000 the HTML code shows, but without CSS, js or images, but when I am looking in the console at the network all the files are there (index.js, style.css, the images);
You can achieve the results you want as follows:
const fs = require('fs');
const port = 5000;
const http = require('http');
const server = http.createServer( function (request, response) {
let filePath = '.'+request.url; //assumes your static files are
// placed in the root directory
if(request.url ==='/' ||request.url==='/index.html'){
filePath = './index.html';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/html');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} else if(request.url==='/index.css'){
filePath = './index.css';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/css');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} //maybe some additional else if for image and so on or you can improve
//this logic but anyway this code gives you the right direction
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});

How serve client javascript modules in node.js

I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:
I have four javascript modules for client side and in HTML I use this code for load javascript moduls:
<script type="module" src="js/controller.js" async></script>
My server code :
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer();
server.on('request', (req, res) => {
let routes = {
'GET': {
'/': indexHtml,
}
}
console.log(req.url)
let handler = routes[req.method][req.url];
handler = handler || readFile;
handler(req, res);
})
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`)
});
function indexHtml(req, res) {
readFile({ url: '/index.html' }, res);
}
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
// console.log(filePath)
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
res.writeHead(200);
res.write(data);
res.end();
}
})
}
How can I solve this error and serve javascript modules, Thanks a lot for your help.
With comment #derpirscher, I change my reader function with this code :
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
const url = req.url === '/' ? '/index.html' : req.url;
if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write(data);
res.end();
}
})
}

Error reading a file with Node js

I can't read a file with this code that I've found on internet...
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
app.get('/', function(req, res) {
fs.readFile('./queries/anagconti_clienti_giorni.txt', 'utf8', function(err, data) {
if (err) {
res.send(err);
} else {
res.send(data);
}
});
});
var server = app.listen(port, function() {
console.log("Started on http://localhost:" + port);
});
The error that it give to me is:
{
"errno":-4058,
"code":"ENOENT",
"syscall":"open",
"path":"C:\Users\AlessandroGolin\Desktop\Mia\Visual_Studio\server_link\queries\anagconti_clienti_giorni.txt
"}
What could be causing this error??
Please cross check the path or permission of "./queries/anagconti_clienti_giorni.txt" file. If file not exist then create your "queries" folder at same level where your above code file exist.

With Express, res.send(data), the browser download the data as a file instead of showing it as HTML webpage

var express = require("express");
var app = express();
var fs = require("fs");
var path = require("path");
app.use('/node_modules', express.static('node_modules'));
app.get("/", function (req,res) {
pathname = path.join(__dirname,"index.html");
fs.readFile(pathname,function (err,data) {
if(err){
throw err;
}
res.send(data);
// the res.send(data), the webpage receive the data, and download it instead of showing it as HTML webpage.
}
)
});
app.listen("3000",function () {
console.log("express server constructed");
})
I will tell you the approachs to do
fs.readFile(pathname,function (err,data) {
if(err){
throw err;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
If you don't want readFile you can use this.
res.sendfile(pathname);
use
res.sendFile(pathname);
instead of
res.send(data);

how to reply a file as a stream in hapi js?

I have an excel file. I want to reply excel file as a stream to the user using hapi JS reply object. I tried like this but it didn't work.
let readStream = fs.createReadStream(filePath);
reply(null,readStream.pipe());
Could anyone suggest me an approach to achieve this?
Use this code for serving file . If files are static files it prints on browser otherthan static files like pdf,excel,word these files will be downloaded .
'use strict';
const Path = require('path');
const Hapi = require('hapi');
var fs = require('fs');
const server = new Hapi.Server();
server.connection({
port: 3000,
host: 'localhost'
});
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/testdoc.docx',
handler: function(request, reply) {
var stream = fs.createReadStream('./testdoc.docx');
stream.on('data', function(data) {
console.log(data);
console.log('loaded part of the file');
//reply(null,data);
reply(data);
});
stream.on('end', function() {
console.log('all parts is loaded');
});
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
run the server node server.js and in browser run as http://localhost:3000/testdoc.docx. Hope this helps.

Resources