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


当前回答

退出

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

其他回答

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之后的任何代码

从nodejs.org官方文档中:

process.exit(code)

使用指定的代码结束进程。如果省略,退出将使用“成功”代码0。

要退出并显示“失败”代码:

process.exit(1);

如果要退出nodejs应用程序,请编写

process.exit(1)

在您的代码中

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

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