concept file in category node

appears as: file, files, files, file, The file, The files
Get Programming with Node.js

This is an excerpt from Manning's book Get Programming with Node.js.

When the installer file is downloaded, double-click the file in your browser’s download panel or your computer’s download folder. The installer opens a new window that looks like figure 1.2 and writes all necessary files and core Node.js libraries to your system. You may be asked to accept licensing agreements or give the installer permission to install Node.js on your computer. Follow the prompts to click through the installation.

  • Loading files into REPL
  • Instead of executing this file with Node.js (which currently wouldn’t offer anything), you initiate the REPL environment with the node keyword and import this file by using .load messages.js, as shown in listing 2.2. By importing the file, you give REPL access to the contents of that file. After the file is imported, the window responds with the file’s contents. You also have access to the messages variable in your REPL environment.

    Listing 2.3. Use a file’s contents in REPL
    > messages.forEach(message => console.log(message));      #1
    Getting MEAN with Mongo, Express, Angular, and Node.js 2ED

    This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.

    In every Node application, you should have a file in the root folder of the application called package.json. This file can contain various metadata about a project, including the packages that it depends on to run. The following listing shows an example package.json file that you might find in the root of an Express project.

    Listing 3.1. Example package.json file in a new Express project
    {
      "name": "application-name",        #1
      "version": "0.0.0",                #1
      "private": true,                   #1
      "scripts": {                       #1
        "start": "node ./bin/www"        #1
      },                                 #1
      "dependencies":                   #2
        "body-parser": "~1.18.3",       #2
        "cookie-parser": "~1.4.3",      #2
        "debug": "~4.1.0",              #2
        "express": "^4.16.4",           #2
        "morgan": "^1.9.1",             #2
        "pug": "^2.0.3",                #2
        "serve-favicon": "~2.5.0"       #2
      }                                 #2
    }

    This listing is the file in its entirety, so it’s not particularly complex. Various metadata at the top of the file is followed by the dependencies section. In this default installation of an Express project, quite a few dependencies are required for Express to run, but you don’t need to worry about what each one does. Express itself is modular so that you can add components or upgrade them individually.

    Common examples include log files and the node_modules folder. Log files don’t need to be up on GitHub for everyone to see, and your Node dependencies should be installed from npm whenever your application is downloaded. You’ll be using Git in section 3.5, so ask the Express generator to create a file for you.

    Serverless Applications with Node.js

    This is an excerpt from Manning's book Serverless Applications with Node.js.

    However, for small applications and situations in which you don’t have a lot of information, you can save money on hosting and maintenance by bundling functionalities related to one service into a single business unit. For your Pizza API, a sensible solution is to have one unit for processing pizzas and orders, one for handling payments, one for handling chatbot functionality, and one for processing images and files.

    The last part of your serverless API is the data layer, which can be similar to the data layer in a scaled monolithic application, with a separately scaled database and file storage service. It would be best if the database and file storage were also independent and autoscalable.

    In the case of your pizza application, it wouldn’t be complete without the images of Aunt Maria’s delicious pizzas. Your cousin Michelangelo (also known as Mike) already took awesome photos of all the pizzas, so you just need to store and serve these static files. AWS has a service for that as well: the Simple Storage Service (S3), which allows you to store the files—up to 5 TB—in a serverless manner.

    Listing 7.4 Convert images to thumbnails
    'use strict'
    const fs = require('fs')
    const path = require('path')
    const exec = require('child_process').exec
    const mime = require('mime')
    const aws = require('aws-sdk')
    const s3 = new aws.S3()
    function convert(bucket, filePath) {    #1  
      const fileName = path.basename(filePath)
    
      return s3.getObject({
        Bucket: bucket,
        Key: filePath
      }).promise()
        .then(response => {
          return new Promise((resolve, reject) => {    #2  
            if (!fs.existsSync('/tmp/images/'))    #3  
              fs.mkdirSync('/tmp/images/')
    
            if (!fs.existsSync('/tmp/thumbnails/'))    #3  
              fs.mkdirSync('/tmp/thumbnails/')
    
            const localFilePath = path.join('/tmp/images/', fileName)    #5  
    
            fs.writeFile(localFilePath, response.Body, (err, fileName) => {    #5  
              if (err)
                return reject(err)
    
              resolve(filePath)
            })
          })
        })
        .then(filePath => {
          return new Promise((resolve, reject) => {    #7  
            const localFilePath = path.join('/tmp/images/', fileName)
            const localThumbnailPath = path.join('/tmp/thumbnails/', fileName)
    
            exec(`convert ${localFilePath} -resize 120x120\\> ${localThumbnailPath}`, (err, stdout, stderr) => {    #8  
              if (err)
                return reject(err)
    
              resolve(fileName)
            })
          })
        })
        .then(fileName => {
          const localThumbnailPath = path.join('/tmp/thumbnails/', fileName)
    
          return s3.putObject({    #9  
            Bucket: bucket,
            Key: `thumbnails/${fileName}`,
            Body: fs.readFileSync(localThumbnailPath),    #10  
            ContentType: mime.getType(localThumbnailPath),    #11  
            ACL: 'public-read'    #12  
          }).promise()
        })
    }
    
    module.exports = convert
    
      #1   Create a handler function that receives the bucket name and S3 file path.
      #2   Wrap nonpromise functions in a JavaScript promise.
      #3   Create images and thumbnails folders in /tmp if they don’t already exist.
      #5   Save the S3 file to the local path.
      #7   Wrap nonpromise functions in a JavaScript promise.
      #8   Resize the image using ImageMagick.
      #9   Put the object back to S3.
      #10   Read the file contents from the /tmp folder.
      #11   Get the MIME type of the file.
      #12   Set the thumbnail ACL.
    Node.js in Action, Second Edition

    This is an excerpt from Manning's book Node.js in Action, Second Edition.

    Node’s core modules are similar to other languages’ standard libraries; these are the tools you need to write server-side JavaScript. The JavaScript standards themselves don’t include anything for working with the network, or even file I/O as most server-side developers know it. Node has to add features for files and TCP/IP networking at a minimum to be a viable server-side language.

    Figure 2.6. The package.json file, when placed in a module directory, allows you to define your module by using a file other than index.js.

    This short example adds the multiparty middleware component and then logs the received files . The files will be uploaded to a temporary location, so you have to use the fs module to delete the files when your application is finished with them.

    To use this example, make sure you’ve installed connect-multiparty.[3] Then start the server and send it a file with curl’s -F option:

    With this configuration, serve-static will check for regular files that exist in ./public/ based on the request URL. If a file exists, the response’s Content-Type field value will be defaulted based on the file’s extension, and the data will be transferred. If the requested path doesn’t represent a file, the next() callback will be invoked, allowing subsequent middleware (if any) to handle the request.

    To test it out, create a file named ./public/foo.js with console.log('tobi'), and issue a request to the server by using curl(1) with the -i flag, telling it to print the HTTP headers. You’ll see that the HTTP cache-related header fields are set appropriately, the Content-Type reflects the .js extension, and the content is transferred:

    $ curl http://localhost/foo.js -i
    HTTP/1.1 200 OK
    Date: Thu, 06 Oct 2011 03:06:33 GMT
    Cache-Control: public, max-age=0
    Last-Modified: Thu, 06 Oct 2011 03:05:51 GMT
    ETag: "21-1317870351000"
    Content-Type: application/javascript
    Accept-Ranges: bytes
    Content-Length: 21
    Connection: keep-alive
    console.log('tobi');

    Because the request path is used as is, files nested within directories are served as you’d expect. For example, you might have a GET /javascripts/jquery.js request and a GET /stylesheets/app.css request on your server, which would serve the files ./public/javascripts/jquery.js and ./public/stylesheets/app.css, respectively.

    Express in Action: Writing, building, and testing Node.js applications

    This is an excerpt from Manning's book Express in Action: Writing, building, and testing Node.js applications.

    Express applications can often be pretty small, even fitting in just one file. As your applications get larger, though, you’ll want to break them up into multiple folders and files. Express is unopinionated about how you scale your app, but it provides one important feature that’s super helpful: subapplications. In Express lingo, these miniapplications are called routers.

    Listing 2.11. Reading a file from disk
    Listing 2.14. Parsing the request URL with a request handler function
    // ... function requestHandler(req, res) { if (req.url === "/") { res.end("Welcome to the homepage!"); } else if (req.url === "/about") { res.end("Welcome to the about page!"); } else { res.end("Error! File not found."); } } // ...

    Run npm install and then create a file called main.js. Put the following inside.

  • Create a file that will be run when Heroku starts your app (called a Procfile). In our simple app, this file will be only one line.
  • Add a file called .gitignore to your project.
  • hapi.js in Action

    This is an excerpt from Manning's book hapi.js in Action.

    If you’ve built web applications, in any language or platform, you’ll know that what sometimes starts out as a simple vision can quickly become complicated. There are numerous things to consider when building a web app, including how to go about caching, validating, and authenticating. You also need to decide how to structure your code into files and directories in a way that makes sense.

    If you use multiple parameters within a single segment, as in the preceding example, you must separate them with at least one valid character that isn’t a parameter. If you had a path such as /download/{file}{ext}, hapi wouldn’t know where to break the final segment into the file and the ext parameters, because there’s no separator.

    Listing 4.21. POST route for uploading files with the default payload configuration
    server.route({ method: 'POST', path: '/upload', handler: function (request, reply) { ... }, config: { payload: { output: 'data', parse: true } } });

    hapi will parse multipart/form-data requests by default. But the way you work with the data from the files varies, depending on the value of the payload.output option in the configuration for the route. We’ll look now at the available options using the HTML form in the following listing as an example for each option.

    4.5.3. Using file output: save the files to disk

    When using the file option, hapi will save any files uploaded through a multipart form directly to the filesystem as temporary files and provide some information, including the file path, inside the request.payload object. Once again, any text fields will be available as strings, as with the other options discussed earlier.

    The typical pattern is to move this temporary file to its intended, final location inside your route handler. The following listing shows the example from earlier, adapted for the file option.

    Listing 4.25. Using the file payload option to write uploads to temporary files
    Node.js in Practice

    This is an excerpt from Manning's book Node.js in Practice.

    fs: Working with files

    Node’s file system module is capable of reading and writing files using non-blocking I/O, but it also has synchronous methods. You can get information about files with fs.stat, and the synchronous equivalent is fs.statSync.

    If you want to use streams to process the contents of a file in a super-efficient manner, then use fs.createReadStream to return a ReadableStream object. There’s more about this in chapter 6.

    Table 6.1. Supported POSIX file methods in Node

    POSIX method

    fs method

    Description

    rename(2) fs.rename Changes the name of a file
    truncate(2) fs.truncate Truncates or extends a file to a specified length
    ftruncate(2) fs.ftruncate Same as truncate but takes a file descriptor
    chown(2) fs.chown Changes file owner and group
    fchown(2) fs.fchown Same as chown but takes a file descriptor
    lchown(2) fs.lchown Same as chown but doesn’t follow symbolic links
    chmod(2) fs.chmod Changes file permissions
    fchmod(2) fs.fchmod Same as chmod but takes a file descriptor
    lchmod(2) fs.lchmod Same as chmod but doesn’t follow symbolic links
    stat(2) fs.stat Gets file status
    lstat(2) fs.lstat Same as stat but returns information about link if provided rather than what the link points to
    fstat(2) fs.fstat Same as stat but takes a file descriptor
    link(2) fs.link Makes a hard file link
    symlink(2) fs.symlink Makes a symbolic link to a file
    readlink(2) fs.readlink Reads value of a symbolic link
    realpath(2) fs.realpath Returns the canonicalized absolute pathname
    unlink(2) fs.unlink Removes directory entry
    rmdir(2) fs.rmdir Removes directory
    mkdir(2) fs.mkdir Makes directory
    readdir(2) fs.readdir Reads contents of a directory
    close(2) fs.close Deletes a file descriptor
    open(2) fs.open Opens or creates a file for reading or writing
    utimes(2) fs.utimes Sets file access and modification times
    futimes(2) fs.futimes Same as utimes but takes a file descriptor
    fsync(2) fs.fsync Synchronizes file data with disk
    write(2) fs.write Writes data to a file
    read(2) fs.read Reads data from a file

    File descriptors (FDs) are integers (indexes) associated with open files within a process managed by the operating system. As a process opens files, the operating system keeps track of these open files by assigning each a unique integer that it can then use to look up more information about the file.

    Although it has file in the name, it covers more than just regular files. File descriptors can point to directories, pipes, network sockets, and regular files, to name a few. Node can get at these low-level bits. Most processes have a standard set of file descriptors, as shown in table 6.2.

    Node has no built-in support for locking a file directly (either mandatory or advisory). But advisory locking of files can be done using syscalls such as flock (http://linux.die.net/man/2/flock), which is available in a third-party module (http://github.com/baudehlo/node-fs-ext).

    Instead of locking a file directly with something like flock, you can use a lockfile. Lockfiles are ordinary files or directories whose existence indicates some other resource is currently in use and not to be tampered with. The creation of a lockfile needs to be atomic (no races) to avoid collisions. Being advisory, all the participating processes would have to play by the same rules agreed on when the lockfile is present. This is illustrated in figure 6.1.

    Figure 6.1. Advisory locking using a lockfile between cooperating processes

    Let’s say we had a file called config.json that could potentially be updated by any number of processes at any time. To avoid data loss or corruption, a config.lock file could be created by the process making the updates and removed when the process is finished. Each process would agree to check for the existence of the lockfile before making any updates.

  • Efficient disk I/O performance —We’re always writing to the end of the file.
  • Durability —The previous state of the file is never changed in any way.
  • A simple way to create backups —We can just copy the file at any point to get the state of the database at that point.
  • Each line in the file is a record. The record is simply a JSON object with two properties, a key and a value. A key is a string representing a lookup for the value. The value can be anything JSON-serializable, which includes strings and numbers. Let’s look at some sample records:

    {"key":"a","value":23}
    {"key":"b","value":["a","list","of","things"]}
    {"key":"c","value":{"an":"object"}}
    {"key":"d","value":"a string"}

    If a record is updated, a new version of the record will be found later in the file with the same key:

    {"key":"d","value":"an updated string"}

    If a record has been removed, it’ll also be found later in the file with a null value: