我想我对全局变量在 nodejs 中的工作方式有点困惑。我有这个代码:
var jsreport = require('jsreport-core')()
var fs = require('fs');
var path = require('path');
// make sure to pass the path to your `helper.js`
var helpers = fs.readFileSync(path.join('/Development/jsreport-new/data/templates/Sample report', 'helpers.js'), 'utf8');
var data = fs.readFileSync(path.join('/Development/jsreport-new', 'scratch.json').toString(), 'utf8');
var json = JSON.parse(data);
jsreport.init().then(function () {
return jsreport.render({
template: {
scripts: [{
content: "request.data={endpoints: json }; done();"
}],
content: fs.readFileSync(path.join('/Development/jsreport-new/data/templates/Sample report', 'content.handlebars'), 'utf8'),
helpers: helpers,
engine: 'handlebars',
recipe: 'phantom-pdf',
phantom: {
"orientation": "portrait",
"format": "A3",
"margin": "3cm",
"headerHeight": "3cm"
},
},
data: {
"books": [
{"name": "A Tale of Two Cities", "author": "Charles Dickens", "sales": 351},
{"name": "The Lord of the Rings", "author": "J. R. R. Tolkien", "sales": 125},
{"name": "The Da Vinci Code", "author": "Dan Brown", "sales": 255},
{"name": "The Hobbit", "author": "J. R. R. Tolkien", "sales": 99},
{"name": "Carlskii", "author": "J. R. R. Tolkien", "sales": 99}
]
}
}).then(function(resp) {
//prints pdf with headline Hello world
console.log(resp.content.toString())
resp.result.pipe(fs.createWriteStream('helloworld4.pdf'));
setTimeout(function() {
process.exit();
}, 3000)
});
}).catch(function(e) {
console.log(e)
});
我需要将从本地文件读取的 json 数据传递给 jsreport 模板。ie 需要传递给模板内的内容content: "request.data={endpoints: json }; done();"
但是,我只是得到[Error: json is not defined]
.
然后我尝试将 json 变量定义为全局变量。例如global.json = JSON.parse(data);
,但是现在有所不同。