簡體   English   中英

如何將變量從 javascript 文件傳輸到 node.js 中的另一個 html 文件?

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

我在 node.js 中有一個項目,旨在從谷歌電子表格中讀取數據,並將該數據存儲在一個數組中,然后在 html 文件中的嵌入式 javascript 中使用。 我最終想在 heroku 上托管這個 node.js 項目,到目前為止它已經成功。 問題是我嘗試執行的所有操作要么在 node.js 中不起作用,要么在我托管時導致我的項目在 heroku 上不起作用。 這是我的 javascript 文件 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 }`))

我一直在嘗試傳輸的變量是 arrx,它是 accessSpreadsheet function 內部的一個局部變量。

您不想使用 console.logging 變量,而是使用“return arrx”來停止 function 並返回該值,或者您可以使用 fs.writefile 將其寫入 html 頁面。 如果您執行前者,則您必須編寫一個單獨的 function 來獲取您返回的值並將 IT 寫入 html 頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM