簡體   English   中英

如何保存txt文件中的數據返回函數之外的數組?

[英]How to save the data from a txt file returns to an array that is outside the function?

這是我第一次使用javascript,我試圖將從.txt文件中提取的數據保存在我在代碼外部和代碼開頭聲明的數組中。 (這是電子框架)。

我試圖提取數據並將其保存到數組中。

const { remote } = require('electron')
const app = remote.app
const $ = require('jquery')
const fs = require('fs')
const dialog = remote.dialog

const win = remote.getCurrentWindow()

let dataMeetingsFromTxt

{...}

function readMeetingsToSaveIntoArray() {
  dataMeetingsFromTxt = []
  fs.readFile('./dataMeetings.txt', 'utf-8', (err, data) => {
    if (err) throw err;
    dataMeetingsFromTxt = data.toString().split("\n");
  })
}

{...}

$('.oneBTN').on('click', () => {
  readMeetingsToSaveIntoArray()
  console.log(dataMeetingsFromTxt.length) //The output is always 'undefined'
})

輸出始終為“未定義”。

這是因為fs.readFile是異步的。 第三個參數是一個回調,這是在console.log中應該完成的地方。 否則,單擊處理程序上的console.log將在readFile的回調之前執行。

const { remote } = require('electron')
const app = remote.app
const $ = require('jquery')
const fs = require('fs')
const dialog = remote.dialog

const win = remote.getCurrentWindow()

let dataMeetingsFromTxt

{...}

function readMeetingsToSaveIntoArray() {
  dataMeetingsFromTxt = []
  fs.readFile('./dataMeetings.txt', 'utf-8', (err, data) => {
    if (err) throw err;
    dataMeetingsFromTxt = data.toString().split("\n");
    console.log(dataMeetingsFromTxt.length);
  })
}

{...}

$('.oneBTN').on('click', () => {
  readMeetingsToSaveIntoArray()
})

暫無
暫無

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

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