Stylus not being applied to my jade file after res.render() - javascript

I cannot seem to compile the stylus file in my project into a css file to be used in conjunction with the jade file. The content of the jade file is being displayed to the browser but it's not being formatted as specified in the .styl file.
I think it has something to do with the paths I'm using. I'm confused in regards to '/public', is that supposed to be a directory I actually create in my project tree or is it simply a placeholder for the current location or something similar?
Below are my required modules:
var express = require('express'),
connect = require('connect'),
account = require('./account'),
stylus = require('stylus'),
nib = require('nib'),
http = require('http'),
path = require('path');
var app = express();
Below is my configuration code:
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
app.configure('development', function(){
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.cookieParser('1234567890QWERTY'));
app.use(express.session({secret: '1234567890QWERTY'}));
app.use(express.errorHandler());
app.use(stylus.middleware({
src: __dirname + '/public',
dest: __dirname + "/css",
compile: compile
}
));
});
Below is my handler:
app.get('/', function(req, res) {
res.render('index',{title: 'Home'});
});
My directory tree currently has my script files under project root, and then the stylesheets, views, css and node_modules directories all also under root. There is no 'public' directory.

app.use(stylus.middleware({
dest: __dirname + '/public',
src: __dirname + "/css",
compile: compile
}
))
The destination should be in the public dir. and your src contains your .styl files

The answer was in where I was calling my app.use(express.static()) command, it needs to come AFTER the code to use the stylus middleware. I found this article informative to solve my question:
[1]: article http://www.quietless.com/kitchen/why-isnt-stylus-compiling-my-css/

Related

How to load JS file in html using express server

I have put my js in a public directory and trying to load the js in my HTML but getting an error.
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Here is my HTML code to load the JS:
<script src="/public/web.js"></script>
directory structure
├ public
| └ web.js
├ views
| └ some.ejs
└ server.js
To serve a file from the server to the client, you must declare the directory as a static.
Using express you can do this using,
app.use(express.static('PublicDirectoryPath'))
To fetch the files under the public directory,
<script src="FilePathUnderPublicDirectory"></script>
Updated Code:
Now your server.js file should be
var express=require('express');
var bodyparser=require('body-parser');
var path=require("path");
var multer=require("multer");
console.log(__dirname);
var app=express();
app.use(express.static('public'));
var upload = multer({ dest: __dirname + '/uploads/' });
// app.set('views', __dirname + '/views');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.render('some.ejs');
});
app.post('/',upload.single('upl'),(req,res)=>{
console.log(req.body);
console.log(req.file);
})
app.listen(3000,()=>{
console.log("server is up");
})
Notice that I declare the public directory as a static directory at
line 7.
Since your web3.js is directly under the public directory, in your front end, use
<script src="/web.js"></script>
For more, please check the doc.
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
app.use(express.static('public'))
now you can serve static files like js, css and images.

failed lookup view with express server and gulp

I'm having a problem connecting an express server with a gulp serve/r task. In order to send my views to the DOM, I need express to do that. I'd like my server to run as a gulp task. The server runs, however when I try to access my local url it runs an error in browser:
Error: Failed to lookup view "index" in views directory "C:\Users\User Name\Documents\project\src\scripts"
My app.js
var http = require('http');
var express = require('express');
var exphbs = require('express-handlebars');
var path = require('path');
var hbs = exphbs.create({ /* config */ });
var app = express();
//environment variable
var port = process.env.PORT || 8000;
// static files + template engine
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, '../scripts'));
app.use('/public', express.static(__dirname + '/public'));
//http request method get json list
app.get('/', function(req, res) {
res.render('index');
});
app.listen(port);
My file structure looks like this:
project
|-- src
| |-- css
| |-- scripts
| |-- app.js
| |-- index.html
What am I missing?
You should change this:
app.set('views', path.join(__dirname, '../scripts'));
to this:
app.set('views', path.join(__dirname, '..'));
This is because the index.html file resides in the src directory which is a parent of the scripts directory from which the script is executed.

How can I go about serving single page html using node.js on port 80?

My project structure looks like this:
project
assets/images/
css/application.css
js/application.js
font
node_modules
index.html
server.js
package.json
My goal is to be able to run 'node server.js" in the project folder and have it serve on port 80. Going to localhost:80 or w.e would render the index.html along with its css/assets/js.
I've tried with connect, express and http but no luck...new to node.
Thanks!
First of all, change your structure:
project
assets/images/
assets/css/application.css
assets/js/application.js
assets/font
node_modules
views/index.html
server.js
package.json
First require some packages:
var express = require('express'),
app = express(),
path = require('path');
Them run in the terminal window:
npm install express
Them set up the configurations:
app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
app.set('env', process.env.NODE_ENV || 'development');
app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
Them create your routes:
app.get('/', function(req, res) {
res.send('Hello word');
});
app.get('/something', function(req, res) {
res.send('Hei, this is something!!!');
});
If you want render the index, inside the views folder:
app.get('/index', function(req, res) {
res.render('index');
});
And finally:
app.listen(app.get('port'), function(req, res) {
console.log('Server listening at ' + app.get('port')');
});
Them access localhost:80/index
Put your assets and subdirs under ./public, then from top dir, add app.js:
var express = require('express');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(80, function () {
console.log('Server running...');
});

Using connect vhost to serve multiple express.js apps

I want to use connect's vhost functionality to deploy several express.js apps to my dev vps. Here is my server.js file that is supposed to send requests to the appropriate place:
var express = require('express')
var quotes = require('quote-of-the-day/lib/app.js');
var server = express();
server.use(express.vhost('inspiringquoteoftheday.com',quotes));
server.listen(80);
Running node server.js throws this error:
Error: Cannot find module 'quote-of-the-day/lib/app.js'
Even though I can cd into app.js straight from the directory where server.js is located.
Here is the lib/app.js file in which I export my express app (I think)
// Generated by CoffeeScript 1.3.3
(function() {
var app, express, pub;
express = require('express');
module.exports = app = express();
pub = __dirname + '/public';
app.use(express["static"](pub));
app.use(express.errorHandler());
app.use(app.router);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function(req, res) {
return res.render('home');
});
}).call(this);
Assuming a directory structure that looks something like this:
|-. quote-of-the-day
|-- server.js <-- the file you list in your question
|-. lib
|-- app.js
Then you should require your app.js with
require('./lib/app');
Might be helpful to use the __dirname global variable here.
it provides 'the name of the directory that the currently executing script resides in.'
thus you could do:
var otherApp = require(__dirname + 'quote-of-the-day/lib/app.js')
http://nodejs.org/docs/latest/api/globals.html

using partials with express in node.js

I am trying to render partials using node.js. Here is my code.
app.js:
var express = require('express')
, routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
var products = require('./products.js');
app.get('/products', function(req, res) {
res.render('products/index', {locals: {
products: products.all
}
});
});
app.listen(3000);
When I go to localhost:3000/products it should render index.jade which is in the products folder which is in the views folder.Above I set the views directory using app.set('views', __dirname + '/views');
index.jade:
h1 Products:
#products!= partial('partials/product', {collection: products})
This should render the partial equivalent to (partials/product.jade) because jade is my view engine.
I am getting an error back saying "partial is not defined"
Any help would be great. thanks
UPDATE:
That solved my partial error thank you. I reinstalled 2.5.9.
Check what version of Express JS you have installed -- you may have the 3.0 alpha:
$ npm ls
...
└─┬ express#3.0.0alpha1
...
If you're interested in trying the alpha, be sure to checkout the documentation on Migrating from 2.x to 3.x. In it, you'll notice that res.partial() and partial() (within templates) have been removed -- as described under "View system changes:"
By removing the concept of a "layout" & partials in Express 3.x template engines will have greater control over file I/O. This means integration with template engines much easier, and greatly simplify the view system's internals.
You can see an example of the intent in the linked article, Use Jade blocks, not layouts.
If you're not interested, then just make sure you have 2.x installed.
$ npm install express#2.x
Or via package.json:
{
...
"dependencies": {
...
"express": "2.x"
}
}

Categories