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. (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. The 3rd args is a call back and this is where the console.log should be done. Else the console.log on your click handler will be executed before the readFile's callback.
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()
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.