1 ---
2 title: Creating Node.js modules
3 redirect_from:
4 - /getting-started/creating-node-modules
5 ---
6
7 Node.js modules are a type of [package][about-pkgs] that can be published to npm.
8
9 ## Overview
10
11 1. [Create a `package.json` file](#create-a-package-json-file)
12 2. [Create the file that will be loaded when your module is required by another application](#create-the-file-that-will-be-loaded-when-your-module-is-required-by-another-application)
13 3. [Test your module](#test-your-module)
14
15 ## Create a `package.json` file
16
17 1. To create a `package.json` file, on the command line, in the root directory of your Node.js module, run `npm init`:
18 - For [scoped modules][scoped-pkg], run `npm init --scope=@scope-name`
19 - For [unscoped modules][unscoped-pkg], run `npm init`
20 2. Provide responses for the required fields (`name` and `version`), as well as the `main` field:
21 - `name`: The name of your module.
22 - `version`: The initial module version. We recommend following [semantic versioning guidelines][semver] and starting with `1.0.0`.
23
24 For more information on `package.json` files, see "[Creating a package.json file][creating-pkg-json]".
25
26 ## Create the file that will be loaded when your module is required by another application
27
28 Create a file with the same name you provided in the `main` field. In that file, add a function as a property of the `exports` object. This will make the function available to other code:
29
30 ```
31 exports.printMsg = function() {
32 console.log("This is a message from the demo package");
33 }
34 ```
35
36 ## Test your module
37
38 1. Publish your package to npm:
39
40 - For [private packages][priv-pkg-pub] and [unscoped packages][unscoped-pkg-pub], use `npm publish`.
41 - For [scoped public packages][scoped-pkg-pub], use `npm publish --access public`
42
43 2. On the command line, create a new test directory outside of your project directory.
44
45 ```
46 mkdir test-directory
47 ```
48
49 3. Switch to the new directory:
50
51 ```
52 cd /path/to/test-directory
53 ```
54
55 4. In the test directory, install your module:
56
57 ```
58 npm install <your-module-name>
59 ```
60
61 5. In the test directory, create a `test.js` file which requires your module and calls your module as a method.
62
63 6. On the command line, run `node test.js`. The message sent to the console.log should appear.
64
65 ## Resources
66
67 <YouTube id="3I78ELjTzlQ" />
68
69 [about-pkgs]: about-packages-and-modules
70 [scoped-pkg]: about-scopes
71 [unscoped-pkg]: creating-and-publishing-unscoped-public-packages
72 [semver]: about-semantic-versioning
73 [creating-pkg-json]: creating-a-package-json-file
74 [priv-pkg-pub]: creating-and-publishing-private-packages#publishing-private-packages
75 [unscoped-pkg-pub]: creating-and-publishing-unscoped-public-packages#publishing-unscoped-public-packages
76 [scoped-pkg-pub]: creating-and-publishing-scoped-public-packages#publishing-scoped-public-packages