Skip to main content

Specifying Paths in Express.js

Hey whassup! This time I'd like to resolve a mess I faced during coding.

There is a function called sendFile() in node. In use cases, it becomes res.sendFile(path_to_file). Specifying file path for res.sendFile() from other directories is a bit tricky!

We have to either use absolute path or specify root for the file location.

( Here is a good article about specifying paths in JavaScript : But unfortunately this is not the solution in our case! ) 

In Express.js most of our works are concentrated on the routes directory, which enables modular coding. So specifying paths for res.sendFile() from routes is not as traditional as in the above linked article, but still simple.

There are two simple ways to do it:

  • res.sendFile(path.join(__dirname, '../our_directory', 'our_file.html'));
  • res.sendFile('our_file.html', { root: path.join(__dirname, '../our_dir') });
The __dirname returns the directory that the currently executing script is in. So use the ../ or ./ stuffs according as your directory hierarchy.

Importantly path is a built-in module, that needs to be required for the above codes to work.
var path = require('path');.

Popular posts from this blog

How to pass variables to res.render() in Node.js

I was trying to figure out how to render a view inside a view, as I was stuck with this issue.

Horrible Effects of Misplaced Extensions ;)
I was using Node.js platform with ejs template engine.

My index.ejs file has an included header.ejs file.
Everything works well except that I can't pass values to the variable status in header.ejs.

Here is my abstract code...




The most funniest solution ever!
The solution is as easy as this.
Just remove .ejs extension from the include command.
I spent at least an entire night to figure it out.

Talky Messenger Documentation & Setup

Just created a chat app that runs in Node and Socket. By the Grace of God, this attempt was worthy.

Talky is a messenger app built with Node, Express, Socket, Angular & Bootstrap.
It's like a server-client structure. (But obviously not like the one we done at OS lab using shared memory). It has a broadcasting structure. Talky does not keep a log on chat. i.e., It doesn't have a memory or database. When we close the browser window, chat history is lost. There I also added a basic console, protected by a password, to send real-time notifications to active clients.

The name 'Talky' was suggested by a friend of mine. (hey, thank you for that. The fact is that I am not really good at naming...😝)

What if sometimes your college blocks WhatsApp? Try Talky.

(There is also a website on internet in the name of 'Talky' which has no connection with this one.)

Download Talky Messenger To use Talky, all you need is 3 things:

Node serverSource code.Three commands.