Skip to content

Instantly share code, notes, and snippets.

@Juul
Last active April 13, 2026 08:13
Show Gist options
  • Select an option

  • Save Juul/9b83007e5566ccbf84c29a015efbaf79 to your computer and use it in GitHub Desktop.

Select an option

Save Juul/9b83007e5566ccbf84c29a015efbaf79 to your computer and use it in GitHub Desktop.
Command-line node.js script to calculate an ISBN from an SBN
#!/usr/bin/env node
// Command-line node.js script to calculate an ISBN from an SBN
// Note that this re-calculates the check digit (the last digit)
// which may not be the correct thing to do.
// Wikipedia claims that it should _not_ be recalculated but cites no sources
function isbnCheck(isbn) {
const str = isbn.toString();
var sum = 0;
var i, number;
for(i=0; i < str.length; i++) {
number = str[i].toLowerCase();
if(number == 'x') number = 10;
sum += (i+1) * parseInt(str[i]);
}
return sum % 11;
}
function sbnToIsbn(sbn) {
if(isbnCheck(sbn.toString())) {
console.error("Invalid SBN!");
process.exit(1);
}
// Prepend 0 and remove old check digit
const str = '0'+sbn.toString().slice(0,-1);
const checkDigit = isbnCheck(str);
var isbn10 = str;
if(checkDigit == 10) {
isbn10 += 'X';
} else {
isbn10 += checkDigit;
}
if(isbnCheck(isbn10)) {
console.error("Conversion failed");
process.exit(1);
}
console.log("ISBN-10:", isbn10);
}
if(process.argv.length != 3) {
console.log("Usage: ./sbn_to_isbn <sbn>");
process.exit(1)
}
sbnToIsbn(process.argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment