如何在MacOS上执行节点js文件?

时间:2018-06-13 19:37:03

标签: node.js macos

我已经在tutorialspoint上启动了Node.JS的教程,但我无法完成第一步:https://www.tutorialspoint.com/nodejs/nodejs_first_application.htm

我是MacOS 10.13.5

我创建了以下名为main.js的js文件。

var http = require("http");

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

它是本教程的复制粘贴,但是当我尝试运行给定的命令node main.js时,没有任何反应。

当我直接在节点CLI中编写代码时,我得到以下响应:

Server {
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] },
  _events:
   { request: [Function],
     connection: [Function: connectionListener] },
  _eventsCount: 2,
  _maxListeners: undefined,
  _connections: 0,
  _handle:
   TCP {
     reading: false,
     owner: [Circular],
     onread: null,
     onconnection: [Function: onconnection],
     writeQueueSize: 0 },
  _usingSlaves: false,
  _slaves: [],
  _unref: false,
  allowHalfOpen: true,
  pauseOnConnect: false,
  httpAllowHalfOpen: false,
  timeout: 120000,
  keepAliveTimeout: 5000,
  _pendingResponseData: 0,
  maxHeadersCount: null,
  _connectionKey: '6::::8081',
  [Symbol(asyncId)]: 192 }

修改 我第一次尝试在命令行中编写它时拼错了响应。我现在修好了,现在得到了上面的回复。

编辑2 这是终端中发生的事情。我包含了ls,所以你可以看到它包含我试图打电话的文件 Picture of terminal

1 个答案:

答案 0 :(得分:1)

运行ps -a | grep node后,我看到我已经有一个进程正在运行。在我杀了它后,我能够执行我的文件。

相关问题