Node.js: import data in DBF format into LibreOffice Calc

Node.js: import data in DBF format into LibreOffice Calc

With Node.js we can import data in DBF format into LibreOffice Calc.

With Node.js we can import data in DBF format into LibreOffice Calc.

Suppose that we have some relevant data scattered across several text files. Each file name contains a brief description of its contents as a slug. The first thing to do is to install the required Node module:


npm install dbf --save

Then we can create the DBF file as follows:


'use strict';

const fs = require('fs');
const pathToDir = './data/';
const files = fs.readdirSync(pathToDir);
const data = [];
const dbf = require('dbf');

function toBuffer(ab) {
    let buffer = new Buffer(ab.byteLength);
    let view = new Uint8Array(ab);
    for (let i = 0; i < buffer.length; ++i) {
        buffer[i] = view[i];
    }
    return buffer;
}

files.forEach(file => {
    if(/\.txt$/.test(file)) {
        let fParts = file.split('.');
        let name = fParts[0].replace(/-/g, ' ' ).toUpperCase();
        let contents = fs.readFileSync(pathToDir + file).toString();
        let part = {
            name: name,
            data: contents
        };
        data.push(part);
    }
});

let buf = dbf.structure(data);
fs.writeFileSync('data.dbf', toBuffer(buf.buffer));

We scan a given directory searching for plain text files. The data provided to the earlier installed module is an array of objects. Each object's property will determine the name of the corresponding table headers once imported into LibreOffice Calc.