LoginSignup
0
0

Node.jsでpy実行時に文字化けしてしまう問題

Posted at

参考URL

文字化け解消のコード

js
const express = require('express');
const bodyParser = require('body-parser');
const { spawn } = require('child_process');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
});
app.post('/python', (req, res) => {
  const message = req.body.message;
  console.log(message);
  let dataToSend;
  //ファイルをコマンドで実行するのと同じ
  const python = spawn('python3', ['./main.py', message], {
    env: { PYTHONIOENCODING: 'cp65001' },//ここで文字コードの指定
  });

  python.stdout.on('data', function (data) {
    console.log('Pipe data from python script ...');
    dataToSend = data.toString();
  });
  python.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
  });
  python.on('exit', (code) => {
    console.log(`Child exited with code ${code}, ${dataToSend}`);
    res.json({ data: dataToSend });
  });
});
app.listen(3000, () => console.log('Server started on port 3000'));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0