If you want to assign file data to a variable, you should try the fs.readFileSync() method.
Synchronous solution
app.get('/test', function(req, res) { var path = __dirname + '/markdown/test.md'; var file = fs.readFileSync(path, 'utf8'); res.send(marked(file.toString())); });
Asynchronous solution
app.get('/test', function(req, res) { var path = __dirname + '/markdown/test.md'; fs.readFile(path, 'utf8', function(err, data) { if(err) { console.log(err); } res.send(marked(data.toString())); }); });
Advanced solution
var Promise = require('bluebird'); // Require 'bluebird' in your package.json file, and run npm install. var fs = require('fs'); var path = require('path'); Promise.promisifyAll(fs); app.get('/test', function (req, res) { fs.readFileAsync(path.join(__dirname, '/markdown/test.md')).then(function(val) { res.send(marked(val.toString())); }); });
As asynchronous programming proceeds to the next step, starting the previous one in a separate thread, access to data assigned asynchronously outside the callback function can lead to a race condition. If you want to use it asynchronously, you can process the response in an asynchronous callback function or convert it to a promise.
Information about Promises:
Asynchronous JavaScript Programming with Promises
Promise.js
Bluebird (Another promise of lib)
source share