Node.js Alert Causes Crash

2019-01-23 02:34发布

I'm trying to create a node.js app and

alert('Sample Alert');

is causing my program to crash. Node says

ReferenceError: alert is not defined

and then quits. I can use the alert function when running javascript on a regular html page, so I'm at a loss to understand why this is... Is this a separate module that I have to use with node.js?

Thanks in advance.

6条回答
欢心
2楼-- · 2019-01-23 02:46

The alert() function is a property of browser window objects. It is not really part of JavaScript; it's just a facility available to JavaScript code in that environment.

Try console.log("Hello World");

查看更多
成全新的幸福
3楼-- · 2019-01-23 02:51

While these answers are "correct", as there is no alert function available outside of the browser, there's no reason you can't create one and then use it:

node -e "function alert(x){ 
            x === 'undefined' ? console.log('undefined') : console.log(x); return; 
         }; 
         alert('x'); alert();"

results:

x
undefined

Then you might not need to change your existing code or example or whatever.

查看更多
Emotional °昔
4楼-- · 2019-01-23 02:52

You'll also need code to wait for a key. Here's a start:

process.stdin.on('char', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write('data: ' + chunk + 'got?\n');
  }
});
查看更多
beautiful°
5楼-- · 2019-01-23 03:03

The alert() property is only allowed by browsers not javascript.

查看更多
该账号已被封号
6楼-- · 2019-01-23 03:05

alert() function is only available when you execute JavaScript in the special context of browser windows. It is available through the window object.

Node.js is not intended for writing desktop applications (directly). It is mainly intended for writing server-side JavaScript applications. You can use following frameworks/packages (and many more) if you want to develop true desktop applications.

  • Electron
  • NW.js (previously, node-webkit)

    NW.js is an app runtime based on Chromium and node.js. You can write native apps in HTML and JavaScript with NW.js. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.

  • AppJS

    Available as an standalone distributable and an npm package


Meanwhile, you can use console.log() to output a message in Node.js.

console.log('hello');
查看更多
一夜七次
7楼-- · 2019-01-23 03:07

alert function is for browsers. means front end..in nodejs for printing in cmd or bash you should use this one..

console.log("Sample alert");

you can print any variable or constant here... for printing variables just remove comma..

查看更多
登录 后发表回答