Is it possible to serve in memory files statically? - javascript

Using express, I am trying to serve a folder statically which was created using an in memory file system. As of yet this has not been working for me, and I am not sure if this is even possible. Here is what I have tried.
const express = require("express");
const Memory = require("memory-fs");
const mfs = new Memory();
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
`;
mfs.mkdirpSync("/public");
mfs.writeFileSync("/public/index.html", html, "utf-8");
const app = express();
app.use(express.static("public"));
app.listen(3000, () => console.log("server is running"));
This code just gives me Cannot GET /. Can this be done?

Related

How to use javascript methd from external files in hbs file

Let's say i have a simple project, index.html and one .js file with a method:
<!DOCTYPE html>
<html lang="pl">
<HEAD>
<script src="controller.js"></script>
<meta charset="utf-8"/>
<title>Project</title>
</HEAD>
<body>
<textarea id ="someID" name = "textFieldName"></textarea>
<button onclick="showNewData()">Button</button>
<p id="score"></p>
</body>
</html>
function getText(){
value = document.getElementById('someID').value;
}
function showNewData(){
getText();
document.getElementById('score').innerHTML = "Current data: "+value;
}
I tried to do the same on localhost:3000. So i've done npm project with express and hbs dependencies. It start from server.js file:
const express = require('express');
const port = 3000;
const app = express();
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port);
In "views" folder i have hbs file looked the same like former index.html file but it can't use javascript method from external file. Does anyone know how to do that?
in hbs file
As far as the browser knows, it is HTML. Clients do not care, and cannot know, if an HTTP response is generated by reading a static file or dynamically with some form of server side processing.
src="controller.js"
The value of the src attribute has to resolve to a URL containing the JavaScript
app.get('/', (req, res) => {
res.render('index')
})
The only URL your web server knows about (and so will provide anything other than a 404 error for) is /.
If you want /controller.js to provide a JS file then you need to write code to make that happen.
How to handle static files is covered in the Express Getting Started Guide.

How to serve html in express.js that references js file from server and run it on client side?

I'm trying to write simplest possible server that serves html page with client side scripts.
Already tried based on http://expressjs.com/en/starter/static-files.html,
Using express.js to serve html file along with scripts, css, and images and
How to load JS file in html using express server, but still I don't get it.
File structure I'm using:
node_modules
resources
resources/page.html
resources/script.js
index.js
package.json
index.js:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(__dirname + '/resources'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname , 'resources', 'page.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
Content
</body>
<script scr="script.js"></script>
</html>
script.js:
var i = 0;
setInterval(() => {
if (i < 10) {
console.log(i);
i++;
}
}, 100);
I type in google chrome browser address localhost:3000/ and page is successfully loader ("Content" string is displayed), but script script.js is not running (empty console). I expect browser to retrieve script.js file and print numbers to console when page.html is loaded.
In the page.html file, change the property scr to src in the script tag and it will work.

Node Express Server : How to serve HTML file properly (scripts and css included) ? (csp, relative path and thing like that)

(I know this question have been asked many times in many form, but I tried a lot of solution and none work the way it should.. So maybe a solution adapted to my work would help me understand.)
Here is the structure of my project.
Here is the index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./../node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-default ">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Brand</a>
</div>
</div>
</nav>
<script src="../node_modules//bootstrap.min.js"></script>
<script src="./../node_modules/jquery/dist/jquery.js"></script>
</body>
</html>
And here is the server/app.js. I let the res.sendFile(); empty on purpose.
//export used
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.get('/', function(req, res){
res.sendFile();
});
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});
The purpose of the server for now is just to send the index.html, that is one level up in the public folder. when a request in made to '/'. and I CAN'T DO IIIITT,
for several reason:
-I tried to use helmet to workaround Content Security Policy.
-I tried to use the static middleware to do stuff..
-I tried to use the path.join / resolve
So is there anyone who can explain somehow how to send this public/index.html file with the bootstrap scripts/css working ?
Have a nice day
Edit:
Here is the new app.js, it render the index.html thanks to the express.static but bootstrap css/scripts are not rendered :
//export used
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.use(express.static(path.join(__dirname, '/..', 'public')));
app.get('/', function(req, res){
res.sendFile('../public/index.html',{root: __dirname});
});
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});
You have to add static middleware just after defining your app and before other routings because it is recommended to put static middleware first.
Use the path module to join the paths since it helps to avoid issues
of operating systems working differently with slashes and backslashes.
app.use( '/' , express.static(path.join(__dirname ,'..' ,'public'));
By doing this, you can serve all your static files in the public directory including scripts and css.
If you are using express, then you shouldn't serve single file instead you can make a static folder where all your js and css lies and you can serve that whole folder and use angular for routing.
Here is sample code:
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.use('/',express.static(__dirname+'public'));
app.use(bodyParser.json());
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});

HTML file not loading js file (NodeJS + Express)

I am running a NodeJS server that serves static files in my public directory. However, my javascript file, main.js, does not run. Below is my code. Any help would be much appreciated.
app.js
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
main.js
function main() {
console.log('test');
};
document.addEventListener('DOMContentLoaded', main);
index.html
<!doctype html>
<html>
<head>
</head>
<body>
<script src="javascripts/main.js"></script>
</body>
</html>
directory structure:
app.js
public
index.html
javascripts
main.js

Add a serverside stored javascript file to html (node.js)

I'm having a small problem with my project.
I'm using node and express for a little webpage .. it is rendering the html page, but the javascript file (test.js) is not sent to the user ..
<!doctype html>
<html>
<head>
<title>Spektrum</title>
<script src="test.js"></script>
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
<style>
canvas{
}
</style>
</head>
<body>
<!-- some stuff -->
</body>
</html>
Node.js file:
var http = require('http'),
fs = require('fs'),
express = require('express'),
app = express();
app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// .....
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
Any idea how to send the javascript file with the html file to the user?
Greetings,
JS
you need to use static middleware to serve file (test.js needs to exist)
example:
// GET /javascripts/jquery.js
// GET /style.css
// GET /favicon.ico
app.use(express.static(__dirname + '/public'));

Categories