简体   繁体   中英

How can I transfer a variable from a javascript file to another html file in node.js?

I have a project in node.js that is designed to read off data from a google spreadsheet, and store that data in an array, which is then used in embedded javascript in an html file. I eventually want to host this node.js project on heroku, which has been sucesseful thus far. The problem is that everything I have tried to do this has either not worked in node.js, or caused my project to not work on heroku when I hosted it. Here is the code from my javascript file, index.js:

const express = require('express');
const GoogleSpreadsheet = require('google-spreadsheet');
const path = require('path');
const PORT = process.env.PORT || 5000;
const { promisify } = require('util');

const creds = require( './clients_secret.json');

var len;


function printVoter(voter){
    len++;
}

async function accessSpreadsheet(){
    const doc = new GoogleSpreadsheet('1q-jrxsY3GUy5KlEvVE6BkXW4BhNYA7QL-Su9seJNY_8');
    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)();
    const sheet = info.worksheets[0];

    const rows = await promisify(sheet.getRows)({
        offset: 1
    })

    rows.forEach(row => {
        printVoter(row);
    })
    global.arrx = new Array(99);
    rows.forEach(row => {
        arrx.push(`${row.regnumber}`);
    })
    arrx.forEach(x => console.log(x));
  console.log(arrx);

}

accessSpreadsheet();




express()
  .use(express.static(path.join(__dirname, 'public')))
  .set('views', path.join(__dirname, 'views'))
  .set('view engine', 'ejs')
  .get('/', (req, res) => res.render('pages/index'))
  .listen(PORT, () => console.log(`Listening on ${ PORT }`))

The variable I have been trying to transfer is arrx, a local variable inside of the accessSpreadsheet function.

Instead of console.logging the variable, you want to either use "return arrx" to stop the function and return that value, or you can us fs.writefile to write it to an html page. If you do the former, you'll have to then write a separate function that takes the value of what you returned and writes IT to an html page.

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