Skip to content

Instantly share code, notes, and snippets.

@amcolash
Last active March 21, 2017 14:47
Show Gist options
  • Save amcolash/008c1937a8b33acfaff23ec05fe1c11c to your computer and use it in GitHub Desktop.
Save amcolash/008c1937a8b33acfaff23ec05fe1c11c to your computer and use it in GitHub Desktop.
Translate a directory of files w/ node

This is a simple node application that will convert a path of files into english names. It does not translate directory names.

You will need to add in your own google translation api key by defining translateKey. Additionally, you will need to run npm install google-translate to the place that you copied translate.js so that you have the translation api dependency.

I made this function synchronous (for better or for worse) using promises to make sure it is all done before continuing on.

Free to use or modify however you want!

const fs = require('fs');
const path = require('path');
const translate = require('google-translate-api');
const non_english_regex = new RegExp('[^\u0000-\u007F]+');
const translateKey = 'YOUR_API_KEY_HERE';
const googleTranslate = require('google-translate')(translateKey);
/* Helper functions */
/* from comment from TifPun located @ https://gist.github.com/kethinov/6658166 */
function walkSync(dir, filelist) {
var files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = walkSync(path.join(dir, file), filelist);
} else {
filelist.push(path.join(dir, file));
}
});
return filelist;
};
function translatePath(dir) {
var results = walkSync(dir);
var promises = [];
if (results) {
for(var i = 0; i < results.length; i++) {
const file = results[i];
const parsedFile = path.parse(file);
if (non_english_regex.test(parsedFile.name) && parsedFile.name.indexOf('%') == -1) {
var promise = new Promise(function(resolve, reject) {
googleTranslate.translate(parsedFile.name, 'en', function(err, translation) {
if (err) {
reject(err);
}
var newName = path.join(parsedFile.dir, translation.translatedText + parsedFile.ext);
fs.rename(file, newName, function(error) {
if (error) {
reject(err);
}
console.log('renamed file: ' + file + ', to ' + newName);
resolve();
});
});
});
promises.push(promise);
}
}
} else {
console.log("no files");
}
return promises;
}
/* Main function */
function main() {
if (process.argv.length != 3) {
console.log('usage: node translate.js [path to translate]');
} else {
console.log("checking path: " + process.argv[2]);
Promise.all(translatePath(process.argv[2])).then(function() {
console.log("translation complete!");
});
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment