如何在本地主机上运行Node.js?

时间:2018-11-30 07:20:17

标签: javascript node.js localhost

这是我第一次使用Node.js,我想在localhost上运行它。我已经安装了Node.js,但是我不知道如何运行本地主机。

你们能帮我吗?以下是我的server.js代码。

setting_detail = {};
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
if (process.env.NODE_ENV == 'production') {
    var cluster = require('cluster');
    if (cluster.isMaster) {
        // Count the machine's CPUs
        var cpuCount = require('os').cpus().length;

        // Create a worker for each CPU
        for (var i = 0; i < cpuCount; i += 1) {
            cluster.fork();
        }

        // Code to run if we're in a worker process
    } else {
        init();
    }
} else {
    init();
}

function init() {
    var port = 5000;
    var config = require('./config/config'),
        mongoose = require('./config/mongoose'),
        express = require('./config/express'),
        db = mongoose(),
        app = express();

    app.listen(port);
    var Settings = require('mongoose').model('Settings');
    Settings.findOne({}, function (error, setting) {
        setting_detail = setting
        console.log('Magic happens on port ' + port);
    });
    module.exports = app;
}

2 个答案:

答案 0 :(得分:1)

您只需要在项目路径中运行node server.js,然后访问-http://localhost:5000

Here 正在为您入门指南。

答案 1 :(得分:-1)

节点的简单程序

var express = require('express');
var app = express();

app.get('/', function (req, res) {
   res.send('Hello World');
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("Example app listening at http://%s:%s", host, port)
})

来源:https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm

猫鼬: https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications