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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53552966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:14:31  来源:igfitidea点击:

How to run Node.js in localhost?

javascriptnode.jslocalhost

提问by faszz tech

This is my first time to use Node.js and I would like to run it on localhost. I had installed Node.js, but I don't know how to run the localhost.

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

can you guys help me? Below is my server.js code.

你们能帮帮我吗?下面是我的 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;
}

回答by Tushar Walzade

You just need to run node server.jsat your project path & then visit this -http://localhost:5000

你只需要node server.js在你的项目路径上运行然后访问这个 - http://localhost:5000

Hereis getting started guide for you.

是您的入门指南。

回答by Vinesh Goyal

Simple Program for node

节点的简单程序

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)
})

Source : https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm

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

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

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