参考:CreatingNode。jsmodules创建package。json文件 因为打算创建公开模块,因此按unscoped的建法。与maven不同,包名貌似不允许中文字符:npminitThisutilitywillwalkyouthroughcreatingapackage。jsonfile。Itonlycoversthemostcommonitems,andtriestoguesssensibledefaults。Seenpmhelpjsonfordefinitivedocumentationonthesefieldsandexactlywhattheydo。Usenpminstallpkgafterwardstoinstallapackageandsaveitasadependencyinthepackage。jsonfile。PressCatanytimetoquit。packagename:(npmmoduledemo)npm模块演示Sorry,namecanonlycontainURLfriendlycharacters。packagename:(npmmoduledemo)npmmoduledemocnversion:(1。0。0)description:entrypoint:(index。js)入口。jstestcommand:gitrepository:keywords:author:license:(ISC)AbouttowritetoUsersxuanwuworkjavascriptappsnpmmoduledemopackage。json:{name:npmmoduledemocn,version:1。0。0,description:,main:入口。js,scripts:{test:echoError:notestspecifiedexit1},author:,license:ISC}IsthisOK?(yes)创建入口文件 入口。js:exports。回应function(){console。log(模块演示);}测试模块 首先需要发布模块到npm。但在运行npmpublish时,报错:npmERR!codeE401npmERR!401UnauthorizedPUThttps:registry。npmjs。orgnpmmoduledemocnYoumustbeloggedintopublishpackages。 发现要先运行npmadduser,创建用户账号。npmERR!codeE403npmERR!403ForbiddenPUThttps:registry。npmjs。orgnpmmoduledemocnyoumustverifyyouremailbeforepublishinganewpackage:https:www。npmjs。comemailedit 还需验证电邮。之后发布成功。 新建测试目录后,添加test。js:var演示require(npmmoduledemocn)演示。回应() 测试目录下安装模块:npminstallnpmmoduledemocn 测试通过:nodetest模块演示