首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node js covert string字符集

Node js covert string字符集
EN

Stack Overflow用户
提问于 2021-09-30 12:10:28
回答 1查看 40关注 0票数 0

我需要将输入的值转换为所选字符集的值。1:https://i.stack.imgur.com/vh07r.png我的代码:

代码语言:javascript
复制
    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);
EN

回答 1

Stack Overflow用户

发布于 2021-10-01 15:11:47

假设您想使用位于path.join(__dirname, '/index.html')的文件内容作为模板,您可以将编码转换的结果注入其中?

如果是这样的话,一个简单的解决方案是:

代码语言:javascript
复制
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();
});

请注意,这只是一个完整解决方案的开始,但这里应该有足够的内容让您入门。

有许多方法可以进行所需的转换,将结果流式传输回调用者会更有效,但这是最简单的解决方案。

两种风格的注释:

  1. Javascript提供了三种定义变量的方法:varletconst,了解每种方法特定用途的原因是很重要的。仅使用let有可能在代码中注入难以调试的错误。
  2. 为提高可靠性,请始终包装可能在try/catch中引发异常的操作,并始终适当地处理捕获的异常。如果不这样做,您将面临无法向调用者返回任何内容的风险,这也会使调试代码变得困难。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69392021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档