양민지
양민지

Reputation: 13

In Node.js , cannot read property 'length' of undefined

I have to make Cryptogram to using node.js Please help ..!!! (And could you make cryptogram key ? ? ) I have tried. . Thanks for your help :)

function encrypt(data,j) {
    for(var i = 0, length = data.length; i<length; i++) {
         j = data.charCodeAt(i);
        //console.log(j);
        String.fromCharCode(j);
        process.stdout.write(j);
    }
    return data;
}

function decrypt(data) {
    return data;
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

process.stdout.write('Input (암호화할 문장을 입력) : ' );

process.stdin.on('data',function(data,j) {
    //data = data.trim();
    process.stdout.write('평문(your input) :' + data);
    process.stdout.write('암호문(encrypt) :');
    encrypt(j);
    process.stdout.write('복호문(decrypt) :');

    process.exit();
    });

Upvotes: 1

Views: 1965

Answers (1)

Jim Schubert
Jim Schubert

Reputation: 20357

process.stdin is a readable stream. The callback accepts a single parameter (see doc example). To be safe, I'd call encrypt() only on on stdin end event. Call that with the concatenation of data.

process.stdin.on('data',function(data) {
    process.stdout.write('평문(your input) :' + data);
    process.stdout.write('암호문(encrypt) :');
    encrypt(data);
    process.stdout.write('복호문(decrypt) :');
    process.exit();
});

If it was me, I would gather all data from stdin as a string (it can be string or Buffer), and process it on the stream's end event:

var input = '';
process.stdin.on('data',function(data) {
    process.stdout.write('평문(your input) :' + data);
    input+=data;
});

process.stdin.on('end', function(){
    process.stdout.write('암호문(encrypt) :');
    encrypt(input);
    process.stdout.write('복호문(decrypt) :');
    process.exit();
});

Upvotes: 1

Related Questions