@yinyinfurong_zmr/dbc-can
Version:
A general purpose CAN (Controller Area Network) toolbox with support for .dbc file parsing, CAN message decoding, and more
45 lines (39 loc) • 1.32 kB
JavaScript
;
var fs = require('fs');
var path = require('path');
/**
* Determines if the containing filepath has the correct extension
*
* @param file Filepath
* @param ext File extension to check against
*/
const validateFileExtension = (file, ext) => {
const fileExt = path.extname(file);
if (fileExt !== ext) {
throw new Error(`Function expected a file extension of '.dbc', got ${fileExt}`);
}
};
/**
* Utility function for Node that allows you to read in a dbc file and output a raw string that can be loaded into
* the Dbc classes .load function.
* @param file File to unload
*/
const dbcReader = (file) => {
validateFileExtension(file, '.dbc');
return fs.readFileSync(file, { encoding: 'ascii' });
};
/**
* Utility function for writing a raw dbc string to a .dbc file
* @param file location and name of the dbc file to write to
* @param fileContent The DBC content that will be loaded into the file
*/
const dbcWriter = (file, fileContent) => {
validateFileExtension(file, '.dbc');
fs.writeFileSync(file, '', { flag: 'w+' });
const lines = fileContent.split('\n');
for (const line of lines) {
fs.writeFileSync(file, `${line}\n`, { flag: 'a+' });
}
};
exports.dbcReader = dbcReader;
exports.dbcWriter = dbcWriter;