用于退出的命令是什么?(即终止Node.js进程)


当前回答

调用全局进程对象的退出方法:

process.exit()

从文档中:

process.ext([exitcode])使用指定的代码结束进程。如果省略,则退出并返回“成功”代码0。要退出并显示“失败”代码:进程.退出(1);执行节点的shell应该看到退出代码为1。

其他回答

退出

let exitCode = 1;
process.exit(exitCode)

有用的退出代码

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - “command not found”
128 - Invalid argument to exit
128+n - Fatal error signal “n”
130 - Script terminated by Control-C
255\* - Exit status out of range

在命令行中,.ext是您想要的:

$ node
> .exit
$

它记录在REPL文档中。REPL(Read Eval Print Loop)是Node命令行的名称。

在正常程序中,使用process.ext([code])。

import mongosse from 'mongoose'
import dotenv from 'dotenv'
import colors from 'colors'
import users from './data/users.js'
import products from './data/products.js'
import User from './models/userModel.js'
import Product from './models/productModel.js'
import Order from './models/orderModel.js'
import connectDB from './config/db.js'

dotenv.config()

connectDB()

const importData = async()=>{
try{
    await Order.deleteMany()
    await Product.deleteMany()
    await User.deleteMany()

    const createdUsers = await User.insertMany(users)
    const adiminUser = createdUsers[0]._id

    sampleProducts = products.map(product =>{
        return {...product, user:adiminUser }
    })
    await Product.insertMany(sampleProducts)

    console.log('Data Imported!'.green.inverse)
    process.exit()      //success and exit

}catch(error){
    consolele.log(`${error}`.red.inverse)
    process.exit(1)   //error and exit

}

}

所以这里我在db和try块中填充了一些集合,如果我没有得到任何错误,那么我们会用一条成功消息退出它,因此我们使用process.exit(),但参数中没有任何内容。如果出现错误,那么我们需要退出并返回一条失败消息,因此我们在参数中传递1,例如process.ext(1)。

额外:这里的退出意味着退出典型的nodejs程序。例如,如果此代码位于名为dbOperations.js的文件中,则process.exit将退出,并且不会运行process.exit之后的任何代码

调用全局进程对象的退出方法:

process.exit()

从文档中:

process.ext([exitcode])使用指定的代码结束进程。如果省略,则退出并返回“成功”代码0。要退出并显示“失败”代码:进程.退出(1);执行节点的shell应该看到退出代码为1。

打开运行节点应用程序的命令行终端,然后按Ctrl+C

如果要从代码中退出node js应用程序,

process.exit(); // graceful termination 
process.exit(1); // non graceful termination