简体   繁体   中英

How can show alert message in node.js

what should i do ?? I work on node.js . I can not use alert("sometext");

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({Email:  req.body.email} , function(err, result) {
  if (result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      window.alert("sometext");
    });
    db.close();
  });
});

output = ReferenceError: window is not defined

NodeJS runs on the console of the given operating system, that said, window.alert is actually a browser API command, you cannot use it, as alternatives, you can:

  1. Use console.log that will output information on the STDOUT(Aka the standard output, aka will just print on the console).
  2. Use console.error, that will do exactly the same as above, but will pipe the content to STDERR, that can be usefull for logging or process output identification purposes.
  3. Wrap your Node application on a container like Electron , that, to be honest, is overkill.
  4. And finally, calling the native dialog API from your OS:

To call a native dialog, you need acess to the OS native libraries, you can do that using the Node FFI module that allows you to bind those libraries. Or, for the sake of simplicity, just use one of existing implementations of that function, like: node-native-dialog , mitsobox or dialog .

Disclaimer: I did not develop or can attest the quality of those modules, use at your own risk, if native dialogs are really required to your development, implement your own binding of the OS libraries.

Assuming you know, which OS you are running on, the most reliable way would be to use it's native shell (so far, most NPM packages I tried did not work out of the box). For windows Powershell, it can look like this:

const { spawnSync } = require('child_process');

const messag = "Hello world";

spawnSync("powershell.exe", [`
Add-Type -AssemblyName PresentationCore,PresentationFramework;
[System.Windows.MessageBox]::Show('${messag}');
`]);

You can also show prompts, like yes / not, etc. See more info here

Update dialog package seems to work out of the box, though does not look to have as much options as what is available with PowerShell.

Install cross-platform, isomorphic alert, for Node and browser (previously alert-node) npm i alert -g

Use this lib:

var alert = require('alert');
alert('Hello');

I can't find where it is documented but I have been using global.alert() in my react-native code for debugging purposes. The app is being controlled by Appium so I can't use console.log .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM