首页 > 解决方案 > 如何在 fs.readFileSync 中使用通配符

问题描述

How do ya make is so 而不是只读取当前文件夹中的 javalin.datasheet ,而是读取所有 *.datasheet 并将它们转换为

我尝试使用 const data = fs.readFileSync('*.datasheet');

但这不起作用,第一次使用 node.js 文件.. 尝试学习一些基础知识。

const fs = require('fs');

const data = fs.readFileSync('javalin.datasheet');

const amountOfColumnsOffset = 0x44;
const amountOfRowsOffset = 0x48;
const headersOffset = 0x5c;
const amountOfBytesInHeader = 12;
const amountOfBytesInCell = 8;

const amountOfColumns = data.readInt32LE(amountOfColumnsOffset);
const amountOfRows = data.readInt32LE(amountOfRowsOffset);

const cellsOffset = headersOffset + amountOfColumns * amountOfBytesInHeader;
const amountOfBytesInRow = amountOfBytesInCell * amountOfColumns;
const stringsOffset = cellsOffset + amountOfRows * amountOfColumns * amountOfBytesInCell;

const headers = [];
for (let i = 0; i < amountOfColumns; i++) {
    const headerOffset = headersOffset + i * amountOfBytesInHeader;
    const stringValue = readStringValue(headerOffset);
    const type = data.readInt32LE(headerOffset + 8);
    headers.push({stringValue, type});
}

const rows = [];
for (let i = 0; i < amountOfRows; i++) {
    const cells = [];
    for (let j = 0; j < amountOfColumns; j++) {
        const cellOffset = cellsOffset + i * amountOfBytesInRow + j * amountOfBytesInCell;
        const cellValue = readCell(cellOffset);
        const columnType = headers[j].type;
        cells.push(parseCellValueToType(cellValue, columnType));
    }
    rows.push(cells);
}

const util = require('util')
console.log(util.inspect(rows, { maxArrayLength: null }))

function parseCellValueToType(cellValue, type) {
    switch (type) {
        case 1:
            const offset = stringsOffset + cellValue.readInt32LE(0);
            let lengthUntilNullTermination = 0;
            let nextByte;
            do {
                nextByte = data.readInt8(offset + lengthUntilNullTermination++);
            } while (nextByte !== 0)
            return data.slice(offset, offset + lengthUntilNullTermination - 1).toString();
        case 2:
            return cellValue.readFloatLE(0);
        case 3:
            return !!cellValue.readInt32LE(0);
    }
}

function readCell(offset) {
    const stringOffset = data.readInt32LE(offset);
    const cellValue = data.slice(offset + 4, offset + 8);
    return cellValue;
}

function readStringValue(offset) {
    const hash = data.slice(offset, offset + 4);
    const stringOffset = data.slice(offset + 4, offset + 8);
    return {hash, stringOffset};
}

标签: javascriptnode.jsfs

解决方案


推荐阅读