Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda