Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Node js covert string charset

I need convert value from my input with value of selected charset. [![To see what i want][1]][1] [1]: https://i.stack.imgur.com/vh07r.png My code:

    const express = require('express');
const app = express();
const path = require('path');
var bodyParser = require('body-parser');
var iconv = require('iconv-lite');


var urlencodedParser = bodyParser.urlencoded({ extended: false });


app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, '/index.html'));
});

app.post('/',urlencodedParser, function(req, res) {
    let input = req.body.input;
    let select = req.body.select;
    let utf8 = iconv.encode(input, 'utf-8');
    let iso = iconv.encode(input, 'iso-8859-1');
    let win = iconv.encode(input, 'win1252');
    console.log(utf8.toString());
    console.log(iso.toString());
    console.log(win.toString());

    
    res.sendFile(path.join(__dirname, '/index.html'));
    res.send(`Input string <textarea character-set=>${input}</textarea><br>
    ISO <textarea character-set="ISO-8859-1"></textarea><br>
    UTF-8 <textarea character-set="UTF-8"></textarea><br>
    Win-1252 <textarea character-set="windows-1252"></textarea><br>
    `); 
});

app.listen(3000);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Presumably, you want to use the content of the file located at path.join(__dirname, '/index.html') as a template into which you can inject the result of the encoding transformation?

If this is the case, a simple solution would be:

const { format } = require('util');

const sourceFilepath = path.join(__dirname, '/index.html');

// Load the html source you wish to return as the result.
// Note that if the file cannot be read, this will throw an 
// exception on server start.
const content = fs.readSync(sourceFilepath);

// The content of content should include a textarea tag in the 
// following format: 
//   `<textarea character-set="%s">%s</textarea>';` 
// where the selected encoding will replace the first `%s` and 
// the resulting encoded input text will replace the second.

// Helper to report errors back to the caller
const reportError = (res, message) => {
  res.status(500).send(message);
  res.end();
};

// Helper to ensure we have a string to encode.
const isNonEmptyString = (s) => (typeof s === 'string') && s.length;

app.post('/', urlencodedParser, function(req, res) {

  // ensure we have something to encode 
  // (trimming leading and trailing spaces.)
  const src = req.body.input.trim();

  if (!isNonEmptyString(src)) {
    reportError(res, 'requires some input to encode');
    return;
  }

  // set the required encoding, using utf-8 as a fall-back.
  const encoding = req.body.select || 'UTF-8';

  // encode the src using the encoding
  // in the case of an encoding error, return a reasonable error message
  // to the caller.

  let result;
  try {
    result = iconv.encode(src, encoding);
  } catch (err) {
    reportError(`Error: failed to convert src using encoding "${encoding}": ${err}`);
    return;
  }
  
  // send back the result after replacing the printf `%s` markers with the
  // selected encoding and the transformed src
.
  res.send(format(content, encoding, result));
  res.end();
});

Note that this is just a start at a complete solution, but there should be enough here to get you started.

There are many ways to do the required transform and it would be more efficient to stream the result back to the caller, but this is the simplest solution.

Two style notes:

  1. Javascript provides three means of defining variables: var, let, and const and it is important to know the reason each has its specific use. Using let only has the possibility of injecting difficult to debug errors in your code.
  2. For reliability, always wrap operations that have the possibility of throwing exceptions in try/catch and always handling caught exceptions appropriately. Without doing this, you run the risk of not returning anything to the caller, which also makes debugging your code difficult.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda