NodeError:在NodeJS中写完后

时间:2018-12-13 16:12:49

标签: javascript node.js

我开始学习NodeJS,并开始制作一个小型应用程序,根据用户单击请求对文件进行加密和解密。下面的代码在第一个加密请求上运行良好,但在另一个请求上崩溃。

App.js

var fs = require('fs')
var crypto = require('crypto')
const express = require('express')
const app = express()
const port = 3000
var key = '1bd';
var cipher = crypto.createCipher('aes-256-cbc', key);
var decipher = crypto.createDecipher('aes-256-cbc', key);


app.use(express.static('public'))


app.get('/', (req, res) => {
    res.sendFile('/enc-dec.html', { root: __dirname })
})

app.post('/encrypt', (req, res) => {
    fs.createReadStream('input.txt')
    .pipe(cipher)
    .pipe(fs.createWriteStream('input.txt.enc'))
    .on('finish', function() {
        res.end("Encrypted")
    });
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

错误:

NodeError: write after end
    at writeAfterEnd (_stream_writable.js:237:12)
    at Cipher.Writable.write (_stream_writable.js:287:5)
    at ReadStream.ondata (_stream_readable.js:646:20)
    at ReadStream.emit (events.js:180:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at ReadStream.Readable.push (_stream_readable.js:213:10)
    at fs.read (fs.js:2123:12)
    at FSReqWrap.wrapper [as oncomplete] (fs.js:680:17)
Emitted 'error' event at:
    at Cipher.onerror (_stream_readable.js:670:12)
    at Cipher.emit (events.js:180:13)
    at writeAfterEnd (_stream_writable.js:239:10)
    at Cipher.Writable.write (_stream_writable.js:287:5)
    [... lines matching original stack trace ...]
    at fs.read (fs.js:2123:12)

我不是那方面的专家,但是 fs 似乎存在问题。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

您的问题是您多次重复使用相同的密码。在流中使用一次后,将无法重用;必须创建一个新的。

您应在请求处理程序中创建密码,如下所示:

multipart/form-data

您似乎还没有完成解密功能,但是在构建解密功能时,还需要将app.post('/encrypt', (req, res) => { var cipher = crypto.createCipher('aes-256-cbc', key); fs.createReadStream('input.txt') .pipe(cipher) .pipe(fs.createWriteStream('input.txt.enc')) .on('finish', function() { res.end("Encrypted") }); }) 下移到请求处理程序中,因为解密器也无法重复使用。