I'm getting the hang of Node.JS/Express.JS plus Stylus, but I have a problem. I tried a lot of things but stylus just wont compile my CSS. I googled it, stackoverflowed it, none of the solutions worked. I guess I'm missing something trivial or looking at the wrong angle. Can you help me out fix stylus to autocompile my css upon PUG template rendering?
Here is ths server.js:
(function initialize(){
//TODO: set dependencies
var express = require('express');
var http = require('http');
var util = require('util');
var stylus = require('stylus');
var image = require('./routes/image');
//TODO: set variables and constants
var port = 8080;
var hostname = 'localhost';
//TODO: create express
var app = express();
//TODO: setup the template engine
app.set('views', './views');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(stylus.middleware({
src: __dirname + '/resources',
dest: __dirname + '/public',
debug: true,
force: true
}));
//TODO: set the default GET route
app.get('/', image.snatch);
//TODO: create the server
var server = http.createServer(app);
//TODO: start the server
server.listen(port, hostname, function start(){
console.log(util.format('Server is running at http://%s:%s/', hostname, port));
});
}());
Here is the image.js:
var snatchImage = function (req, res){
var html = res.render('snatchImage',
{
title: 'Hey',
message: 'Hello there!'
});
return res.send(html);
};
exports.snatch = snatchImage;
This is the PUG file:
doctype html5
html
head
title= title
link(rel='stylesheet', href='/css/style.css')
body
div(rel='stylesheet', href='/style.css', class="selection")= message
If I missed something here is the git, maybe it will be more clear to view it like that. Git link.
Related
I am new to node express (started with node long time ago but didn't do much) and I would like to learn how to use it. I am going through some of my older work and reading lots of tutorials but I just can't seem to get this one working.
I have this app that reads data from some sensors on serial port and sends it to sesors.ejs. I would like to reprogram it in express. I have the sensor reading in terminal but not in ejs.
old (working) app.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
const { SerialPort } = require('serialport')
const { ByteLengthParser } = require('#serialport/parser-byte-length')
const port = new SerialPort({ path: 'COM4', baudRate: 9600 })
const parser = port.pipe(new ByteLengthParser({ length: 30 }))
var sensors = fs.readFileSync('views/sensors.ejs');
var app = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end(sensors);
});
var io = require('socket.io').listen(app);
io.on('connection', function(data){
console.log
});
parser.on('data', function(data){
console.log(data.toString("UTF8"));
io.emit('data', data.toString("UTF8"))
});
app.listen(3000);
old (working) sensors.ejs
<script>
var socket = io();
socket.on('data', function(data){...}
</script>
This works great.
I went through several express routing tutorials but I don't know how to send io data to router.
I have c/p most of the code from old app.js to new sensor.js in routes dir, without fs, app.listen etc. I have c/p sensors.ejs to views folder.
In new app.js I have:
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sensorsRouter = require('./routes/senzori');
var app = express();
app.set('views', path.join(\__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(\__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/senzori', sensorsRouter);
index.ejs and users.ejs (fetch mysql data) are working (express is installed and working)
Thanks
I have found the solution. If anyone else with my level of "knowledge" needs the solution, here it is:
I have moved reading serial port to bin/www
The only code in sensors.js is:
router.get('/', function(req, res, next) {
res.render('sensors');
});
I have deployed an app to Heroku but my images arent appearing. They all work fine in localhost. The app runs using express and handlebars.
I have seen it could be as a result of case sensitivity and have checked the case is the same for .png. So i assume its a pathing issue. I have used background.png in CSS at that works correctly its only images referenced in HTML.
Heres the image
<img class="logo" alt="logo" src="images/logo.png"> <!-- Logo image -->
Localhost
Heroku
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The project structure
background.png CSS
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../Images/background.png");
The issue was the syntax images was lower case when the folder name is Images. Creating the 404.
Here is my express code:
const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');
// create the express app
const app = express();
var cors = require('cors');
app.use(cors());
app.use("/",serveStatic ( path.join (__dirname, '/dist') ) );
app.use('/static', express.static(path.join(__dirname, '/dist23')));
app.listen(port, () => {
console.log("listening on "+port)
});
The above code only works for the folder /dist. But when I go to /static, it shows a blank page and this error in the console:
If I put the js files from /dist23 into /dist, then /static works and shows me the application. Its almost like it is looking for files inside /dist and not /dist23. How do I fix it?
Both apps were built using vue-2.6.11. Both directories have files built/bundled for production.
You need to set the content type while serving your static files.
app.get('/index.html', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
app.get('/', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
I am building a quick Express JS application. I have sent data to Redis from another application.
I did an LPUSH. I was able to do this:
client.lrange('stash', 0, 10, function(err, reply) {
console.log(reply);
});
My goal is to, instead of doing a console.log("..."), I want to send it to a in my index.html.
Any ideas on how to do this?
EDIT: Here is my app.js file:
var express = require('express');
var redis = require('redis');
var app = express();
app.use(express.static('public')); //used to get image
app.engine('html', require('ejs').renderFile); //ejs, not handlebars
function index(req,res, next) {
testController.index(req, res, next);
}
app.get('/', function(req, res){
res.render('index.html');
});
app.get('*', function(req, res){
res.render('404.html');
});
//redis stuff
var client = redis.createClient();
client.on('connect', function() {
console.log('connected');
});
client.lrange('stash', 0, 10, function(err, reply) {
console.log(reply); //instead of this, let's place that into a div
});
//end redis
app.listen(3000, function(){
console.log('My example app is now running! (3000)')
});
from my understanding you could use ejs to plug in data directly into your html. The problem of course is that I don't know how client.lrange works but I know that express reads middleware top to bottom. If lrange is pulling data you need from the db you can save the data to a global var data and on a call to the endpoint of the html you want updated; render it with ejs.
create a place holder for the data
var data;
pull the data from server and save globally
client.lrange('stash', 0, 10, function(err, reply) {
data = reply;
});
render html page with ejs using ejs tags
app.get('/', function(req, res) {
res.render('index.html', {reddisData: data});
});
plug it into your html
<a>
<%= reddisData %>
</a>
all together
var express = require('express');
var path = require('path');
app = express()
app.engine('html', require('ejs').renderFile);
app.set('html', 'ejs');
var data;
client.lrange('stash', 0, 10, function(err, reply) {
data = reply;
});
app.get('/', function(req, res) {
res.render('index.html', {reddisData: data});
});
Hope this helps, if it doesn't work for you the idea is what counts. Look into using ejs to resolve your problem.
I'm trying to install Ghost to my node app. I followed the configuration instructions and got it running with, however when I navigate to the blog subdirectory it just shows my site's homepage. I'm passing it the express app instance to start the server. What am I doing wrong?
var ghost = require('ghost');
ghost().then(function (ghostServer) {
app.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(app);
});
I read online about running Ghost with ngynx or apache and configuring it to do some kind of proxy thing, but I don't really understand what all that's about.
Here is a working version of app.js for express and ghost subdirectory setup. Notice how your express routes need to be wrapped in the ghost.then() callback.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ghost = require('ghost');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
ghost().then(function (ghostServer) {
app.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
});
module.exports = app;
const ghost = require('ghost')
const express = require('express')
const path = require('path')
const { getSubDir } = require('./node_modules/ghost/core/server/services/url/utils')
const app = express()
ghost().then((ghostServer) => {
app.use('/games', express.static(path.join(__dirname, 'games')))
app.use(getSubdir(), ghostServer.rootApp)
ghostServer.start(app)
})
latest howto included here:
https://docs.ghost.org/docs/using-ghost-as-an-npm-module