Including and automatically compiling Sass on Express server - node.js

So I have a basic Express project set up and I'm using this github project, https://github.com/andrew/node-sass, to be able to use Sass on top of node. This is my app.js currently:
var io = require('socket.io'),
express = require('express'),
path = require('path'),
routes = require('./routes'),
jquery = require('jquery');
/**
* Create app
*/
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
/**
* Configure app
*/
app.configure(function(){
app.set('port', 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
});
What do I need to do to get Sass working and auto recompiling? I can't seem to find any useful info for Express servers specifically.

First add this require statement:
var sass = require("node-sass");
and then the following code, in your app.configure block:
...
app.use(sass.middleware({
src: <your-sass-files-dir>,
dest: path.join(__dirname, 'public'),
debug: true
}));
...
But I'm sorry to say that the node-sass library is quite useless at the moment, because the #import's, in your scss files, does not work as it's supposed to... See https://github.com/andrew/node-sass/issues/27 for current status.
UPDATE 2013-10-22: Apparently the issue mentioned above seems to be fixed according to #jonathanconway in the comments below... Though there's still an unanswered comment on the issue from someone that still experiences the error at 2013-09-03

Like joakimbeng said, currently the node-sass library has an issue where the #import's are kind of broken.
However! I found a workaround, which you can see here.
What I did basically is grab the raw sass (in my case, scss), and let node-sass render the string for me. But, since it's current working directory is wherever your server.js file is located, you're going to have to put url's in your sass file, relative to your server.js. In my case, like this.

Related

Find a css file node js

Hi I'm new to nodejs and I've just succeed to deploy a nodejs app online. Now I would like to know how to link CSS, JS or image files be cause when I try to do it like I used to, I get the error GET (not found).
The folder architecture is:
--public
--assets
--css
index.css
--js
--views
--index.ejs
--node modules
app.js
package.json
Assuming that I want to code the link index.css in index.ejs, what I need to write in my app.js file please.
app.js code:
var express = require('express');
var app = express.createServer();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.render('index');
});
app.listen(8080,'IP_ADRESS');
index.ejs code:
<link rel="stylesheet" type="text/css" href="/css/index.css">
The basic set up of serving static files in express :
var express = require("express");
var app = express();
...
app.use(express.static(__dirname + '/public'));
...
app.listen(3000);
Now in your .ejs in order to load the css styles or js scripts :
<link rel="stylesheet" href="/css/index.css"/>
First, there's a thing called a static file. Basically, that's a file that's sent over the internet without any kind of modification. Image and CSS files are typically static files.
It looks like you've put your static files in a folder called public.
Express has a built-in feature for sending static files, called express.static. You can use it like this:
// Require the modules we need.
var express = require('express');
var path = require('path');
// Create an Express app.
var app = express();
// Get the path to the `public` folder.
// __dirname is the folder that `app.js` is in.
var publicPath = path.resolve(__dirname, 'public');
// Serve this path with the Express static file middleware.
app.use(express.static(publicPath));
// ...
You should now be able to see static files. If your site is normally accessible at http://localhost:3000, you'll be able to see index.css at http://localhost:3000/css/index.css.
If you want to know way too much about express.static, you can check out a blog post I wrote that goes into Express's static files in depth.

Visual Studio Code - Node.js - Cannot find name '__dirname'

Just to preface I'm not a professional coder, but nonetheless I got roped into building a website for my boss after he found out I took "Web Design" in high school 10 years ago. Back then static sites were fine, and heck CSS was just starting to show it's potential, but I digress.
I'm working on a Node.js project on Visual Studio Code right now and have a weird exception. The code works fine, but I guess it's just curiosity at this point. Anyway, here's my code.
app.js
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
multer = require('multer'),
controller = require('./controllers');
//Sets the view engine to jade.
app.set('views', __dirname + '/frontend');
app.set('view engine', 'jade');
//sets up the development enviroment
if (app.get('env') === 'development') {
app.locals.pretty = true;
app.use(express.static(__dirname + '/build/public'))
var build = require(__dirname + '/build.js');
app.use('css/*', function(req, res, next){
build.style();
next();
});
}
//Sets up the public directory to serve static files - This will be depricated quite soon...
//app.use(express.static(__dirname + '/public'));
//Initalizes site-wide local variables
//app.set('title', 'Halvorson Homes');
//Sets up body-parser to be able to read RESTful requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(multer({dest: 'tmp'}).fields());
//Load Controllers
app.use( '/' , controller);
//makes the app listen on port 3000
app.listen(3000, function() {
console.log('Listening on port 3000...');
})
My folder structure is pretty much as follows
controllers
index.js
designs.js
models
designs.js
frontend
common
layout.jade
header.jade
footer.jade
client.js
style.less
index
index.jade
client.js
style.less
designs
index.jade
client.js
style.less
build
tmp
srv
app.js
build.js
package.json
According to VS Code's built in debugger there's exceptions on lines 8, 14, and 15. They're the only places I used __dirname in the entire project. This is an annoying to me, as I am too much of a perfectionist. Is it Node, VS Code, or something else?
The warning you are getting is from the eslint extension. While it may be valid in Node.JS, it's warning you about __dirname because it's not valid in all JavaScript environments such as in browsers.
To suppress the warning you will want to create an .eslintrc file in your project's root directly and indicate that the code will be running in node like so:
{
"env": {
"node": true
}
}
You can see the .eslint file used to configure eslint for the actual vscode codebase here https://github.com/microsoft/vscode/blob/main/.eslintrc.json
Late to the party, but just had the same issue. The fix for me was to add the node types so VSCode recognises them:
Go to the Terminal view, then enter the following:
npm install #types/node --save-dev
Then hit Cmd + Shift + P (for Mac at least) to bring up the VSCode command search dialogue, then select Reload Window.
When it reappears, that error and any other related to Node.JS stuff not being recognised should be gone.
Alternatively to creating a separate .eslintrc file, you can also add it to the package.json file.
The docs state:
To specify environments in a configuration file, use the env key and specify which environments you want to enable by setting each to true. For example, the following enables the browser and Node.js environments
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
}
}

Stylus not working on Express

I have a project that uses Nib and Stylus on Express server, and after some changes this compilation process from .styl to .css didn't work anymore, I was looking in documentation of Nib, Stylus and Express but I can't find an answero to problem because my code, file directory and settings seems ok. But still doesn't compile.
Code:
express = require("express")
coffee = require("coffee-script")
stylus = require("stylus")
jade = require("jade")
nib = require("nib")
app = express.createServer()
port = process.env.PORT || 3000
app.use app.router
app.use express.methodOverride()
app.use express.bodyParser()
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use stylus.middleware(
src: __dirname + "/src"
dest: __dirname + "/public"
compile: (str, path) ->
stylus(str).set("filename", path).set("warn", true).set("compress", false).set("paths", [ require("stylus-blueprint") ]).use nib()
)
app.listen port
After looking into documention, Github issues, I can't understand what changes have been made to stop working. So, my question, how or what I should be looking for to try resolve this problem?
Thanks for the help in advance.
It would be useful if you provided a error output/log and a cakefile.
Also you might want to look into using connect-assets. A good example of usage is in the express-coffee template.

how to set path to the views (template) directory and to static files in node.js

I have created layout.jade, navigation.jade, and index.jade, and I want to glue them together.
In server.js, how do I
set the path to the views (template) directory, and
set the path to static files.
Is it required that node_module be placed in the folder that contains server.js?
Below is the code for server.js:
//create an app server
var express = require("express");
var server = express.createServer();
//set path to the views (template) directory
app.set('views', D:\#Programming\node.js\trial box\views);
//set path to static files
//how is the path to static files set?
app.use(express.static(__dirname + '/../public'));
//handle GET requests on /
app.get('/', function(req, res){
res.render('index.jade', {title: 'web project'});
});
//listen on localhost:3000
app.listen(3000);
Thank you in advance.
This questions a little old, but I'll still leave an answer. You'll need to place your app.use(... statement inside a callback function for app.configure() like so..
app.configure(function(){
app.use(express.static(__dirname + '/../public'));
});
You should use the express bin tool to bootstrap a project you'd get all that setup.
To install it:
sudo npm install express -g

Expressjs not recognizing static files

I have a nodejs app and am using expressjs. I've defined my static directory, but when I access it, it doesn't load. My express config is:
var app = express.createServer().listen(8001);
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use('/public', express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({ secret: "appsession" }));
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
});
Inside my /public directory I have 3 folders, css, js, and img. Inside css I have a style.css. When I try to access it directly via http://localhost:8001/public/css/style.css I get: Cannot GET /public/css/style.css
Any ideas what I could be doing wrong?
Thanks!
EDIT:
It seems to be related to how I have my routes setup. I'm doing it like this:
var routes = require('./routes')(db);
pp.get('/', routes.index);
Then in my index.js file, I have:
module.exports = function(db) {
return {
index: function(req, res, next) {
res.render('index');
}
}
}
I have my error handling enabled, but when I use the routing in this way, it doesn't use expresses error handling, however if I take this out, it does.
You setup the static http middleware as follows:
app.use(express.static(__dirname + '/public'));
And retrieve a file in ./public/css/style.css with the url:
"/css/style.css"
public is not part of the path when you actually request the file.
Change your static handler to this:
app.use('/public/css', express.static(__dirname + '/public/css'));
Then http://localhost:8001/public/css/style.css should get what you want
Full sample app that allows curl http://localhost:8001/public/css/style.css:
app.js
|-public
|-css
|-style.css
var express = require("express"),
app = express.createServer();
app.use('/public/css', express.static(__dirname + '/public/css'));
app.listen(8001);
Was running into the same issue found the answer here
https://github.com/senchalabs/connect/issues/298
When you have try to use nested files it kinda get lost,
it says fixed on the tracker a year ago, however i tried today and worked fine
I figured it out.
I have two services running on my host. Django is running the site at the root: http://myURL.com, and then Node is running at http://myURL.com/node
The configuration is fine with all the files in Node. The index.html file is requested fine, but the index.html when it requests the stylesheets and static files, the request gets caught by Django before it makes it to Node. Django saw the file and had no idea what it is and returned the 404 error.
By disabling Django from catching the requests to those files it all works fine.

Resources