返回提供降价与明码标记
所以我正在运行一个小的testing应用程序来返回一个路由被访问时在html中的降价文件的内容。 我正在使用标记来呈现降价( https://github.com/chjj/marked )。
在这里,我们到目前为止 –
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)) })
当我导航到本地主机:3000我越来越 –
TypeError:不能调用未定义的方法'replace'请把这个报告给https://github.com/chij/marked 。
我相当肯定我试图发送一个string,它res.send('Hello World!')工作得很好。 对不起,我是新来的两个节点和快递,所以我仍然搞清楚事情。 任何帮助深表感谢。
如果要将文件的数据分配给variables,则应尝试fs.readFileSync()
方法。
同步解决scheme
app.get('/test', function(req, res) { var path = __dirname + '/markdown/test.md'; var file = fs.readFileSync(path, 'utf8'); res.send(marked(file.toString())); });
asynchronous解决scheme
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())); }); });
Promisified解决scheme
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())); }); });
因为asynchronous编程将进入下一步,在单独的线程中运行前一个,访问callback函数外asynchronous分配的数据可能会导致争用情况。 如果要asynchronous使用它,可以在asynchronouscallback函数中处理响应,或者将其转换为承诺。
承诺信息:
带有约定的JavaScriptasynchronous编程
Promise.js
蓝鸟 (另一个承诺lib)