Search code examples
mysqlnode.jsencodinglatin1node-mysql

Convert mysql query from latin1 to utf8 using nodejs


I have a database in latin1 and I want to convert its queries to utf-8.

Example:

response.write returns this JSON:

{"questions":[{"question":"Nação","answer":"País"}]}

But I need it converted to utf8:

{"questions":[{"question":"Nação","answer":"País"}]}




conexao_bd.getConnection(function(err,con){
            if(err) return console.log("Erro na conexao. "+err);
            con.query("SELECT question, answer FROM "+tipo+" WHERE id IN "+c,function(err, rows){
                if(err) console.log("Erro na query questions: "+err);
                else{
                    for(var k =0;k<rows.length;k++)
                        perguntas.questions[k]={'question': rows[k].question,'answer':rows[k].answer};
                    console.log(JSON.stringify(perguntas));
                    con.release();
                    response.writeHeader(200, {"Content-Type": "text/plain"});
                    response.write(JSON.stringify(perguntas));
                    response.end();
                }
            });

        });

Solution

  • Re-coding strings as posted by @bodokaiser is also a possibility, but it is not a clean system solution. The clean solution is to tell the database to give you utf-8. This can be done in two ways:

    1. Set the connection charset using a query set names utf8.
    2. Set the connection charset when you create connection. Don't know if this is possible in node.js. If not use the above option.