vue electron read file 1

vue electron read file

import fs from 'fs'
import readline from 'readline'
import iconv from 'iconv-lite'

ipcMain.on('readfile', async (event, arg) => {
    await readLines()
    event.sender.send('readfile-reply', 'complete')
})

function readLines() {
    return new Promise((resolve, reject) => {
        stream = fs.createReadStream(filePath).pipe(iconv.decodeStream('shift-jis'))
        let reader = readline.createInterface(stream, {})
        reader
            .on('line', line => {
                insertLine(line)
            })
            .on('close', () => {
                resolve() // "Resolve" in the close event.
            })
            .on('error', function(err) {
                reject(err)
            })
    })
}

Here is what the above code is Doing:
1. The ipcMain.on() function is listening for a message from the renderer process.
2. When the message is received, the readLines() function is called.
3. The readLines() function returns a promise.
4. The readLines() function creates a read stream from the file.
5. The read stream is piped through iconv-lite to convert the encoding to UTF-8.
6. The read stream is piped to the readline module.
7. The readline module reads the file line by line.
8. Each line is passed to the insertLine() function.
9. When the file is finished reading, the promise is resolved.
10. The promise is resolved by sending a message back to the renderer process.

Similar Posts