我正在使用 Electron-vue 进行开发。我想逐行读取用户提供的大文本文件。另外,我想在阅读过程中显示一个加载图标(这意味着阅读应该是异步的)。
请注意,文本文件是用 shift-jis 编码的。
起初,我尝试了以下方法:
src/renderer/components/Import.vue
const dialog = require('electron').remote.dialog
export default {
name: 'import',
data () {
return {
loading: false
}
},
methods: {
mounted () {
this.$refs.search.focus()
},
openDialog () {
let filePath = dialog.showOpenDialog({
properties: ['openFile'],
})
this.loading = true
let that = this
// Use the async function.
this.getResultFileRead(that, filePath[0]).then(function (res) {
// When the async function is completed, remove the loading icon.
that.loading = false
console.log(res)
})
},
// Define async function here.
async getResultFileRead (path) {
return this.$electron.ipcRenderer.sendSync('readfile', path)
}
}
}
src/main/index.js
import fs from 'fs'
import readline from 'readline'
import iconv from 'iconv-lite'
ipcMain.on('readfile', (event, arg) => {
// Using stream to decode shift-jis file.
stream = fs.createReadStream(filePath).pipe(iconv.decodeStream('shift-jis'))
let reader = readline.createInterface(stream, {})
reader.on('line', line => {
insertLine(line)
})
reader.on('close', () => {
// do other stuff
})
event.returnValue = 'complete'
})
但这些都不起作用。当提供一个文件时,该文件是异步读取的,但是一旦提供了文件(即在完成操作之前),readfile 函数就会返回“完成”,因此加载图标永远不会出现。
如何在电子 vue 上同时实现“使用 shift-jis 异步读取文件”和“在读取文件时显示加载图标”?请注意,Electron-vue 似乎使用的是 Node.js 版本 8.9.3。