Sandro Rey
Sandro Rey

Reputation: 2989

Getting name property from package.json with NodeJS

I would like to know if there is a way in NodeJs to get the name property from my project package.json file:

{
    "name": "bendiciones",
    "version": "1.12.0",
    "description": " bendiciones",
    "main": "main.js",
    "scripts": {
...
}

I've tried with

import {name} from './package.json';
import {name} from './app.json'

but I got the errors:

TS2307: Cannot find module './package.json'.
TS2307: Cannot find module './app.json'.

I've tried also with:

 console.log ('--2>', process.env.npm_package_name);

but I get undefined

Upvotes: 3

Views: 7594

Answers (5)

yeerk
yeerk

Reputation: 2697

If you are using pure Javascript with no loaders you will have to load the package.json file manually:

import { readFileSync } from "fs";

// ./package.json is relative to the current file
const packageJsonPath = require.resolve("./package.json");

const packageJsonContents = readFileSync(packageJsonPath).toString();

const packageJson = JSON.parse(packageJsonContents);

console.log(packageJson.name);

Upvotes: 2

Karol Majewski
Karol Majewski

Reputation: 25810

If you're using TypeScript, this becomes easy:

import pkg from '../path/to/package.json';

pkg.name;

It does require the following compilerOptions in your tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

Upvotes: 5

Harsh Patel
Harsh Patel

Reputation: 6830

I also want to do the same and here's the code that worked. Since it uses require to load the package.json, it works regardless of the current working directory.

var packageFile = require('./package.json');
console.log(packageFile);

A warning:

Be careful not to expose your package.json to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too. Such specific data can be used by an attacker to better fit the attack on your server.

Upvotes: 0

Sergey Mell
Sergey Mell

Reputation: 8040

I had a similar issue. As a solution, you should add a custom typing i.e. json-loader.d.ts with the content

declare module "*.json" {
    const value: any;
    export default value;
}

Upvotes: 5

Dan Knights
Dan Knights

Reputation: 8368

You can require the entire file and choose whichever properties you want:

const packageJSON = require("path/to/your/package.json");

console.log(packageJSON.name);

Upvotes: 4

Related Questions