Skip to content

Instantly share code, notes, and snippets.

@einfallstoll
Created July 10, 2014 06:25
Show Gist options
  • Save einfallstoll/bd1f81d351b39d1d0c3c to your computer and use it in GitHub Desktop.
Save einfallstoll/bd1f81d351b39d1d0c3c to your computer and use it in GitHub Desktop.
Converts a file to utf-8 in node.js
var fs = require('fs')
if (!process.argv[2]) {
console.log('Please specify a path')
} else {
fs.stat(process.argv[2], function(error, stats) {
if (error) throw error
if (stats.isDirectory()) {
console.log('Now starting conversion...')
convertFolder(process.argv[2])
} else {
console.log('Now starting conversion...')
convertFile(process.argv[2])
}
})
}
function convertFolder(path) {
console.log('Convert everything in folder', path)
fs.readdir(path, function(error, files) {
if (error) throw error
files.forEach(function(filename) {
fs.stat(path + '/' + filename, function(error, stats) {
if (error) throw error
if (stats.isDirectory()) {
convertFolder(path + '/' + filename)
} else {
convertFile(path + '/' + filename)
}
})
})
})
}
function convertFile(path) {
console.log('Convert file', path)
fs.readFile(path, {
encoding: 'utf8'
}, function(error, content) {
if (error) throw error
fs.writeFile(path, content, {
encoding: 'utf8'
}, function(error) {
if (error) throw error
console.log('Successfully converted', path)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment