这是我第一次使用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是异步的。第三ARGS是回电,这是控制台的地方。否则,在ReadFile的回调之前将执行Console.log。
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()
})