Justin
Justin

Reputation: 45340

Read and block from stdin in node.js

How can I have our node.js application halt/block, waiting on stdin before running the rest of the code? I have:

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var ECRYPTION_KEY;
rl.question('Provide the global encryption key:', function(encyrptionKey) {
    ECRYPTION_KEY = encyrptionKey;
    rl.close();
});

var https = require('https');

https.createServer({ ... });
console.log("https server running...");

Right now, I see Provide the global encryption key: and also https server running.. immediately. I.E. does not block and wait on stdin before creating the https server.

Upvotes: 0

Views: 403

Answers (2)

alex
alex

Reputation: 12265

You cannot do that. Ever. Node.js is designed to run without blocking all the time, and waiting for stdin to do something is a misuse.

PS: Actually you can (with fibers) but it is not a good reason to use them.

adeneo's advice is right, just put createServer function inside your callback.

Upvotes: 0

maček
maček

Reputation: 77778

The server is being created before the encryption key is received from the rl callback.

Upvotes: 1

Related Questions