Getting error TS2304: Cannot find name 'Buffer'
Asked Answered
V

8

62

I am trying to do base64 encode in NodeJS using TypeScript.

Following code working fine in JavaScript.

When I am writing same thing in TypeScript and compiling, I am getting Buffer is not find error.

var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');

Can someone help me to do same thing in TypeScript.

Vengeance answered 10/8, 2016 at 13:51 Comment(0)
P
64

Add this line at top:

declare const Buffer

and it should compile without errors.

Declarations is required to use node built in libraries or other global objects, you can manually declare it like above.

With new version of Typescript, you can also use official declaration files:

npm i -g typescript@next
npm i --save-dev @types/node

for other libraries, install @types/library_name.

more details: Improve Declaration File Acquisition, The Future of Declaration Files

Pup answered 10/8, 2016 at 15:35 Comment(1)
I guess this would be apt - npm i --save-dev @types/node. Dev dependencies!Lula
S
71

For the IONIC 4 developers, I installed it using

npm install --save @types/node

When I tried adding "types": ["node"] as shown below

"compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"]
},

to the

tsconfig.json

it did not work. I had to add the entry to

tsconfig.app.json

Please refer to the following link for relevant documentation.
https://github.com/aws/aws-sdk-js/issues/1271#issuecomment-291658668

Let me know if that worked for you!

Scrope answered 31/10, 2019 at 13:49 Comment(3)
Well, that didn't work in an Angular 12 app. Installed the types, added to tsconfig.app.json, but still seeing "Buffer is not defined" in the browser console :/Pansophy
@Pansophy if you found a solution, can you provide it here please ? :DScholarship
Node's Buffer class doesn't exist in a browser context, so web frontends need to use a different approach. One such approach is described in this answer: https://mcmap.net/q/319808/-getting-error-ts2304-cannot-find-name-39-buffer-39Sherillsherilyn
P
64

Add this line at top:

declare const Buffer

and it should compile without errors.

Declarations is required to use node built in libraries or other global objects, you can manually declare it like above.

With new version of Typescript, you can also use official declaration files:

npm i -g typescript@next
npm i --save-dev @types/node

for other libraries, install @types/library_name.

more details: Improve Declaration File Acquisition, The Future of Declaration Files

Pup answered 10/8, 2016 at 15:35 Comment(1)
I guess this would be apt - npm i --save-dev @types/node. Dev dependencies!Lula
D
30

Prologue

Buffer is part of the Node.js API. Because TypeScript doesn't know classes from Node.js by default, you will need to install declaration files (type definitions) for Node.js.

If you see the following error, you will have to install type definitions manually:

error TS2304: Cannot find name 'Buffer'.

Installing Type Definitions

You can install type definitions using the typings tool. I will show you how to do this:

  1. Install the typings tool with npm:

    npm install -g typings

  2. Install type definitions for Node.js from the DefinitelyTyped (~dt) repository:

    typings install dt~node --global --save

The typings tool will create the following directory "typings/globals/node" and link it in "typings/index.d.ts". There will be also a file called typings.json (because of the --save option), which references the resolved type definitions:

{
  "globalDependencies": {
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

Note: If you see the error "typings\globals\node\index.d.ts(71,26): error TS1110: Type expected", then your Node.js definition is too recent. The typings tool has issues with latest type declarations. In such a case, just check the version in your typings.json file. For me node#6.0.0+20160621231320 was working but node#6.0.0+20161212163245 was not.

  1. Now all you have to do is adding index.d.ts as a triple-slash directive within your code (which uses the Buffer class):

YourClass.ts

/// <reference path="../../typings/index.d.ts" />

export class YourClass {

  private static toString(encoded: string): string {
    return new Buffer(encoded, "base64").toString();
  }

}

UPDATE:

With the release of TypeScript 2.0 a new type definitions system has been announced.

You can now forget about the typings tool. All you need to do is running this command to install TypeScript definitions for Node.js:

npm install --save @types/node

Please also make sure that you have the following entries in your tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "node",
    ...
  },
  "exclude": [
    "node_modules",
    ...
  ]
}

P.S. If you need type definitions for other classes (than included in Node.js), you can search for them here: http://microsoft.github.io/TypeSearch/

Dinerman answered 15/12, 2016 at 10:12 Comment(2)
I've been fighting this for days and this is the first time I've seen a solution that actually works with a windows 10 environment. Thanks!Ctesiphon
Unfortunately, as nice as this is for fixing my windows environment issues it broke OSX environments. ;( Getting a typescript error: Typescript Error Subsequent variable declarations must have the same type. Variable 'extensions' must be of type 'any', but here has type 'NodeExtensions'.Ctesiphon
T
20

For Angular users:

  1. Run the following command

npm install --save @types/node

  1. In your tsconfig.app.json file, add these two lines to the CompilerOptions:
"compilerOptions": {
    //...
    "types": ["node"],
    "typeRoots": ["node_modules/@types"]
  }
Talent answered 20/8, 2020 at 15:17 Comment(1)
This worked for me, but how these instructions are resolving the issue??Laszlo
I
17

Buffer is from Node namespace. First install

npm install --save @types/node

then add below code to your tsconfig.json file inside the compilerOptions section

"types": ["node"],
"typeRoots": ["node_modules/@types"]

The typeRoots entry specifies a list of directories for type definition files to be included. It requires TypeScript version 2.0 or later.

Inellineloquent answered 3/1, 2019 at 15:15 Comment(3)
Installing @type/node npm install --save @types/node, wasn't suffice. I had to add "types": ["node"] to my tsconfig.json. Thank youTol
I followed all the steps, but still getting the errorCydnus
I found the solution, (I am using Angular), the src/tsconfig.app.json has to be updated rather than tsconfig.json, here is a reference to the issue in Github: github.com/aws/aws-sdk-js/issues/1271#issuecomment-320352814Cydnus
E
5

To fix this issue in Karma/Jasmine

  1. Run

npm install --save @types/node

  1. In your tsconfig.spec.json file, add these two lines to the CompilerOptions:
"compilerOptions": {
    //...
        "types": [ "jasmine" , "node" ],
        "typeRoots": ["node_modules/@types"]
  }
Earshot answered 10/12, 2020 at 12:32 Comment(1)
This was the only solution that worked for me. I am using Angular and Jasmine so this is probably the solution for other people using Angular and want to use Node types for Angular tests. Thanks!Bentham
S
4

Since I wanted to use Buffer with typescript in a browser context, the only solution for me was to install the buffer package.

npm install buffer

And then, in the file where you want to use it,

import { Buffer } from 'buffer/';
Sherillsherilyn answered 8/6, 2022 at 4:26 Comment(3)
Exactly what I needed for an Angular project!Handiwork
How to import using require in a nodejs project. Becasuse import statement can only be used inside moduleRutland
Lifesaver! Not sure why that trailing slash is important, but it is. Without the slash worked in Node, but failed in Bun.Kulda
P
2

This solution worked for me.

npm i -S @types/node

Then in tsconfig.json

"angularCompilerOptions": {
    "types" : ["node"]
    ....
}

https://fireflysemantics.medium.com/adding-types-node-to-angular-84a629976c86

Polenta answered 28/11, 2023 at 6:4 Comment(1)
With angular 17 this works shinyJoslin

© 2022 - 2024 — McMap. All rights reserved.