Refund the displayed markdowns using express and marking

So, I am launching a small test application to return the contents of the markdown file in html when visiting the route. I use tagged for rendering markdowns ( https://github.com/chjj/marked ).

Here is what I still have -

app.get('/test', function(req, res) { var path = __dirname + '/markdown/test.md' var file = fs.readFile(path, 'utf8', function(err, data) { if(err) { console.log(err) } return data.toString() }) res.send(marked(file)) }) 

When I go to localhost: 3000, I get -

TypeError: it is not possible to call the "replace" method from undefined Report this https://github.com/chij/marked .

I'm sure I'm trying to send a string and it res.send ("Hello World!") Works fine. Sorry, I'm new to Node and expressing, so I still understand. Any help is greatly appreciated.

+5
source share
1 answer

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)

+8
source

Source: https://habr.com/ru/post/1211193/


All Articles