[英]How to save the data from a txt file returns to an array that is outside the function?
It's my first time using javascript and I'm trying to do is save the data extracted from a .txt file in an array that I've declared outside and at the beginning of the code. 这是我第一次使用javascript,我试图将从.txt文件中提取的数据保存在我在代码外部和代码开头声明的数组中。 (It's Electron framework).
(这是电子框架)。
I tried to extract the data and to save into the array. 我试图提取数据并将其保存到数组中。
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'
})
The output is always 'undefined'. 输出始终为“未定义”。
This is because fs.readFile is asynchronous. 这是因为fs.readFile是异步的。 The 3rd args is a call back and this is where the console.log should be done.
第三个参数是一个回调,这是在console.log中应该完成的地方。 Else the console.log on your click handler will be executed before the readFile's callback.
否则,单击处理程序上的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.