Ejemplos Básicos

Cómo escribir un archivo


const fs = require('fs')

const content = 'This is the content of the file'

// Write to a file (creates it if it doesn't exist)
fs.writeFile('myfile.txt', content, (err) => {
  if (err) {
    console.error('Error writing to the file:', err)
    return
  }
  console.log('File saved successfully')
})
        

Cómo leer un archivo


const fs = require('fs')

// Read a file asynchronously
fs.readFile('myfile.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err)
    return
  }
  console.log('File content:', data)
})
        

Cómo leer un archivo async/await


const fs = require('fs')

// Read a file synchronously
async function readFile(name) {
  try {
    const data = await fs.readFileSync(name, 'utf8')
    console.log('File content:', data)
  } catch (err) {
    console.error('Error reading the file:', err)
  }
}

readFile('myfile.txt')
        

Cómo leer un archivo de datos JSON


/* person.json
{
  "name": "John Doe",
  "phone": "555-1234",
  "address": "123 Sunny Boulevard, Miami FL"
}
*/

const fs = require('fs')
const data = fs.readFileSync(name, 'utf8')
const person = JSON.parse(data) // Parse the file content as an object
console.log('Name', person.name)
console.log('Phone', person.phone)
console.log('Person', person)
        

Cómo crear un servidor web


const http = require('node:http')
const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello World')
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})