Jin's rambling

BOM issue with csv

Node.js, Express.js에서 csv 파일 다운로드 기능을 제공하려고 하는데, BOM 때문에 애 먹었다.

아직 이해가 안 되지만, data buffer랑 최종 output data에 둘 다 BOM 값을 추가해야 제대로 된 파일 포맷으로 다운로드가 되었다.

const csvData = 'someCsvData';

// first need to add BOM to the beginning
const bomBuffer = Buffer.from([0xEF, 0xBB, 0xBF]);
const csvBuffer = new Buffer(csvData);
const combinedData = Buffer.concat([bomBuffer, csvBuffer]);

res.set('Content-Type', 'text/csv; charset=utf-8');
res.attachment('report' + fromDate + '_' + toDate + '.csv');

// then for some reason, need to send BOM along with the combined data... don't know why.
res.status(200).send('\uFEFF' + combinedData);

fast-csv를 사용해서 파일을 write할 때, BOM값 입력하기

csv.writeToString(dataList, {headers: true}, function(err, data) {
    if (err) {
        return reject(err);
    }
    fs.writeFile("output.csv", '\ufeff' + data, { encoding: 'utf8' }, function(err) {
        /* The actual byte order mark written to the file is EF BB BF */
        if (err) {
            return reject(err);
        }
        resolve();
    });
});