简体   繁体   中英

Confusion over global variables and how to use them

I think I'm a little confused as to how global variables work in nodejs. I have this code:

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)
});

I need to pass the json data that read from a local file to a jsreport template. ie It needs to be passed to the content within the template content: "request.data={endpoints: json }; done();"

However, I just get [Error: json is not defined] .

I then tried defining the json variable as global variable. eg global.json = JSON.parse(data); , however it makes now difference.

Your json variable here isn't actually global. It's local to your node module's scope, and no other modules will be able to access it.

This means, by the time your report parses and executes "request.data={endpoints: json }; done();" from within its own scope, it isn't aware of json .

To answer your question about when to use global variables, the slightly snarky but valid answer is "never." Managing data accessibility is always recommended. Instead, I recommend you include the json data in the context value directly, like so:

scripts: [{
    content: "request.data={endpoints: " + JSON.stringify(json) + " }; done();"
}] 

I have never used node.js but based on your results

[Error: json is not defined].

I am led to believe the problem relates to the following

var data = fs.readFileSync(path.join('/Development/jsreport-new', 'scratch.json').toString(), 'utf8');
var json = JSON.parse(data);

json is not given a value because data fails to declare, or at least, not declare properly.

I suggest you write the value of data to the console, then figure it out from there.

console.log(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM