[英]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.